Recently I’ve faced a weird bug about displaying image from URL to UIImageView
. Finally I found out is the header issue.
Let’s take an example, there are 2 images
Image1 has the header
1 2 3 4 5 6 7 8 9 10 11 12 HTTP 200 No ErrorServer : AmazonS3Content -Type: binary/octet-streamLast -Modified: Mon, 01 Jul 2013 03 :06 :03 GMTx -amz-meta-type: image/jpegx -amz-request-id: 8845 F67C90997FF6Date : Fri, 15 Nov 2013 04 :02 :30 GMTx -amz-id-2 : F9crPjTya1RNjUeaNLkE2cQTOet8WnAk72idgXeXBIglwwxHLVBvWbL67IC4BrkmAccept -Ranges: bytesContent -Length: 127456 Etag : "545ccc75ee7fc045ed201092742af52e"
Image2 has the header
1 2 3 4 5 6 7 8 9 10 HTTP 200 No ErrorServer : Microsoft-IIS/8 .0 Content -Type: image/jpegX -Powered-By: ASP.NETLast -Modified: Thu, 24 Oct 2013 21 :41 :42 GMTAccept -Ranges: bytesDate : Fri, 15 Nov 2013 04 :07 :30 GMTContent -Length: 60585 Etag : "16e91dd41d1ce1:0"
Look at the Content-Type
, Image1 with the Content-Type
binary/octet-stream (if you type the URL in browser it will force download) , while Content-Type
of Image2 is image/jpeg (it will display in browser if you type in the URL) .
Solution I make a plain HTTP request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 NSString *url = @"http://example.com/image1.jpg" ;AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]]; [httpClient setParameterEncoding:AFFormURLParameterEncoding]; NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:url parameters:nil ]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { UIImage *image = [UIImage imageWithData:responseObject]; imageView.image = image; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog (@"Error: %@" , error.description); }]; [operation start];
instead of (this will only work for Content-Type: image/jpeg
)
1 2 3 4 NSString *url = @"http://example.com/image1.jpg" ;[[AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] success:^(UIImage *image) { imageView.image = image; }] start];