I use the following code to download the profile picture from a Facebook user’s friends array:
NSString *urlString = friendData[#"picture"][#"data"][#"url"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:2.0f];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
UIImage *image = [UIImage imageWithData:data];
}];
urlString is valid, i.e. I can open it in Safari, and I do see the picture there.
In the completion handler, error is nil, and data has 1583 bytes.
However, image is initialized as nil, i.e. image could not be initialized from the specified data.
What is wrong with my code?
EDIT (due to the comment of rckoenes):
resp contains the following data:
{ status code: 200, headers {
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "max-age=1209600, no-transform";
"Content-Length" = 1583;
"Content-Type" = "image/jpeg";
Date = "Thu, 01 Oct 2015 09:19:41 GMT";
Expires = "Thu, 15 Oct 2015 08:08:18 GMT";
"Last-Modified" = "Thu, 01 Oct 2015 06:36:27 GMT";
"timing-allow-origin" = "*";
} }
Try this code
Download AsyncImageView Class Here
.M File
#import "AsyncImageView.h"
NSString *urlString = friendData[#"picture"][#"data"][#"url"];
AsyncImageView *DescimageRight = [[AsyncImageView alloc]initWithFrame:CGRectMake(4,4,146,146)];
DescimageRight.contentMode = UIViewContentModeScaleAspectFill;
DescimageRight.backgroundColor=[UIColor clearColor];
DescimageRight.tag=999;
DescimageRight.imageURL=[NSURL URLWithString:urlString];
[self.view addSubview:DescimageRight];
I found the problem:
The code is correct, and the image is also loaded correctly.
The problem was that I set a breakpoint to the last line of the code, i.e. to
}]; // breakpoint was set here
Apparently, when the debugger stops there, it left already the scope of the completion handler, and image was already nil.
After I inserted a dummy statement behind the assignment to image, and set the breakpoint to this dummy statement, everything was OK.
Sorry for bothering you.
Related
I'm trying to download a 94KB image file from my server. I've tried two ways to do this: using NSURLSession dataTaskWithURL and NSData dataWithContentsOfURL.
NSURLSession:
Globals *global = [Globals getInstance];
// GET request to /mobile/image
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/mobile/image/%#", [global rootUrl], self.photoId]];
NSURLSession * session = [global session];
NSDate *start = [NSDate date];
[[session dataTaskWithURL:url completionHandler:^(NSData *imgData, NSURLResponse *response, NSError *error) {
NSLog(#"Time taken: %f", [[NSDate date] timeIntervalSinceDate:start]);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ([httpResponse statusCode] != 200) {
// error
} else {
dispatch_async(dispatch_get_main_queue(), ^ {
UIImage *image = [UIImage imageWithData:imgData];
CGFloat width = self.photoImageView.frame.size.width;
CGFloat height = image.size.height / image.size.width * width;
self.imageHeight.constant = height;
self.photoImageView.image = image;
});
}
}] resume];
NSData:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
Globals *global = [Globals getInstance];
// GET request to /mobile/image
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/mobile/image/%#", [global rootUrl], self.photoId]];
NSDate *start = [NSDate date];
NSData *imgData = [NSData dataWithContentsOfURL:url];
NSLog(#"Time taken: %f", [[NSDate date] timeIntervalSinceDate:start]);
UIImage *image = [UIImage imageWithData:imgData];
CGFloat width = self.photoImageView.frame.size.width;
CGFloat height = image.size.height / image.size.width * width;
dispatch_async(dispatch_get_main_queue(), ^{
self.imageHeight.constant = height;
self.photoImageView.image = image;
});
});
Here is the output for my NSLog for how long they took to complete:
NSURLSession:
Time taken: 6.585221
Time taken: 3.619189
Time taken: 4.408179
Time taken: 9.931350
Time taken: 3.689192
NSData:
Time taken: 0.157747
Time taken: 0.135785
Time taken: 0.576947
Time taken: 0.462661
Time taken: 0.337266
Taking 3~10 seconds to download a simple <100KB image file is unacceptable, so I'm currently just sticking with NSData, but I need to use NSURLSession later for another similar image download task because I need login sessions.
I'm wondering if I've accidentally discovered a weird bug with NSURLSession, if it's just supposed to be much slower because it has all the overhead of sessions, or if I'm doing something wrong.
Edit:
I figured it out, thanks for all your help!
I created a whole new project with all the connections of this one, and it performed fine.
Problem: The previous VC that before this was calling dataTask multiple times. I was completely baffled why that would affect this VC. Turned out that the class was called ViewController (default name), and this VC was inheriting ViewController instead of UIViewController.
Therefore, calling [super viewDidLoad] from the viewDidLoad of this ViewController was actually calling the previous VC and running all those dataTasks all over again.
When in doubt, check all the other connections in the session.
You're having a threading problem. Do not run that code (the NSURLSession code) in a background thread! Run it on the main thread. Don't worry, this won't block the main thread; the whole point of NSURLSession is that it operates asynchronously so that you don't have to.
I faced with a strange problem. I load file from the Internet using NSURLSession and NSURLSessionDownloadTask. Here is the code
NSURLSessionConfiguration *sessionConfiguration =
[NSURLSessionConfiguration backgroundSessionConfiguration:kSessionId];
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:[NSOperationQueue new]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
[downloadTask resume];
My class is declared as NSURLSessionDownloadDelegate and I get callbacks well. But when the system calls the delegate method
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(#"totalBytesExpectedToWrite: %lld", totalBytesExpectedToWrite);
NSLog(#"%lld", totalBytesWritten);
}
totalBytesExpectedToWrite always equal -1 and I have no ability to show a progress to user because I don't know the downloading file's size.
Could you prompt me where I made a mistake?
-1 is NSURLSessionTransferSizeUnknown, which means that the http server did not provide
a "Content-Length" header (and the data is sent using "Transfer-Encoding: chunked").
There is probably not much that you can do. You could try if the workaround from https://stackoverflow.com/a/12599242/1187415 works in your case as well:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
[request addValue:#"" forHTTPHeaderField:#"Accept-Encoding"];
The web service may not be providing the total size in the header field Content-Length.
If the total size is not provided there is no way for your app to know the length and this provide a progress bar.
Check what is coming from the web server with a analyzer such as Charles Proxy.
The Content-Length can be non 0 and totalBytesExpectedToWrite:-1
//TRACK PROGRESS - MOVED DOWN as also used in BACKGROUND REFRESH > DOWNLOAD FILE > CALL DELEGATE
-(void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//to see response header
NSLog(#"downloadTask.response:%#\n", downloadTask.response);
// { status code: 200, headers {
// "Cache-Control" = "no-cache";
// "Content-Disposition" = "attachment; filename=Directory.zip";
// "Content-Encoding" = gzip;
// "Content-Length" = 33666264;
// "Content-Type" = "application/octet-stream";
// Date = "Tue, 27 Oct 2015 15:50:01 GMT";
// Expires = "-1";
// Pragma = "no-cache";
// Server = "Microsoft-IIS/8.5";
// "X-AspNet-Version" = "4.0.30319";
// "X-Powered-By" = "ASP.NET";
// } }
NSDictionary *responseHeaders = ((NSHTTPURLResponse *)downloadTask.response).allHeaderFields;
NSString * contentLengthString = responseHeaders[#"Content-Length"];
double contentLengthDouble = 0.0f;
if (contentLengthString) {
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
NSNumber *contentLengthNumber = [f numberFromString:contentLengthString];
contentLengthDouble = [contentLengthNumber doubleValue];
}else{
}
NSLog(#"contentLengthString:[%#]", contentLengthString);
//You can get progress her
NSLog(#"bytesWritten:%lld", bytesWritten);
NSLog(#"totalBytesWritten:%lld", totalBytesWritten);
//DONT USE CAN BE ALWAYS -1 for Gzip
NSLog(#"totalBytesExpectedToWrite:%lld", totalBytesExpectedToWrite);
//avoid DIV by 0
if (contentLengthDouble > 0.0) {
double percentage1 = (totalBytesWritten / contentLengthDouble);
double percentage = percentage1 * 100.0;
NSLog(#"PERCENTAGE DOWNLOADED:[%f%%]", percentage);
}else{
NSLog(#"PERCENTAGE DOWNLOADED:[contentLengthDouble is 0]");
}
NSLog(#"=========");
}
The following is Output over and over as zip is downloaded.
but totalBytesExpectedToWrite:-1
So you need to check Content-Length in downloadTask.response
2015-10-27 16:04:18.580 ClarksonsDirectory[89873:15495901] downloadTask.response:<NSHTTPURLResponse: 0x7f9eabaae750> { URL: http://asset10232:50/api/1/dataexport/ios/?lastUpdatedDate=01012014000000 } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Disposition" = "attachment; filename=Directory.zip";
"Content-Encoding" = gzip;
"Content-Length" = 33666264;
"Content-Type" = "application/octet-stream";
Date = "Tue, 27 Oct 2015 16:03:55 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
contentLengthString:[33666264]
bytesWritten:47278
totalBytesWritten:33606690
totalBytesExpectedToWrite:-1
PERCENTAGE DOWNLOADED:[99.823045%]
I am writing a sample app to test how AFNetworking can be used as a replacement for ASIHTTPLib.. The old library made it simple to upload a file to an Apache server (provided the user has write access to a URL/directory). No other server side support is used..
This code has some problem, but I have not pinpointed it: executing the method reports an upload success, but the plist file on the cloud side does not change…
-(void)uploadReminders:(NSArray*)reminders
{
NSLog(#"AppDelegate Synch Reminders to cloud");
//NSLog(#"Data: %#", reminders);
[self persistReminders:reminders atCustomPath:nil];
NSString *cacheDirectoryPath = [self cachesDirectoryPath];
NSString *urlString = [NSString stringWithFormat:#"%#/%#",kStandardCloudAreaAccessURL,kStandardLocalCachePlistFile];
//NSLog(#"URL: %#", urlString);
NSString *remindersPlistFile = [NSString stringWithFormat:#"%#/%#",cacheDirectoryPath,kStandardLocalCachePlistFile];
//NSLog(#"Filepath: %#",remindersPlistFile);
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:kStandardCloudAreaAccessUsername password:kStandardCloudAreaAccessUserPW persistence:NSURLCredentialPersistenceNone];
/**/
NSURL *url = [NSURL URLWithString:urlString];
NSString *host = [url host];
NSInteger port = [[url port] integerValue];
NSString *protocol = [url scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setURLCredentialStorage:credentials];
[configuration setHTTPAdditionalHeaders: #{#"Accept": #"text/plain"}];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager.securityPolicy setAllowInvalidCertificates:YES];
manager.responseSerializer = [AFPropertyListResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
NSURL *URL = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:remindersPlistFile];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Upload Error: %#", error);
} else {
//NSLog(#"Upload Success");
NSLog(#"Upload Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
}
The console shows this:
Upload Success: <NSHTTPURLResponse: 0x8d4ec50> { URL: https://[.....]/CodeTests/Reminders/Reminders.plist } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = "Keep-Alive";
"Content-Length" = 1324;
"Content-Type" = "text/plain";
Date = "Mon, 10 Mar 2014 14:48:13 GMT";
Etag = "\"3f06e5-52c-4f430180dae80\"";
"Keep-Alive" = "timeout=5, max=100";
"Last-Modified" = "Sun, 09 Mar 2014 17:48:26 GMT";
Server = "Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.7l DAV/2";
} } {
reminders = (
{
completed = 1;
created = "2014-03-09 17:47:41 +0000";
description = "";
title = Reminder;
updated = "2014-03-09 17:47:41 +0000";
},
{
completed = 1;
created = "2014-03-08 09:47:58 +0000";
description = "Orza!!! Ma orza in fretta... Ah: funziona? Ebbene, s\U00ec! O no?\n";
title = "Reminder Orza";
updated = "2014-03-08 11:39:43 +0000";
},
{
completed = 0;
created = "2014-03-07 11:09:59 +0000";
description = "Whatever you like; and of course you can even make it quite long.\n\nYeooww..\nReally long!\n\n\n\n";
title = "Reminder A";
updated = "2014-03-08 11:34:24 +0000";
}
);
version = "1.0";
}
The only catch is that when I reopen the app, it jumps back to the test reminders I did manually put on the server: the Reminders.plist gets never changed.
Thanks!
I'm assuming your NSLog of the responseObject is confirming that the plist was successfully received by the server. If so, then that may eliminate the above "upload" code as the source of the problem. You may want to inspect the data on your server (not through the app, but manually inspect it yourself) and see whether your new list of reminders is there or not. It seems that there a couple of possible logical possibilities:
If the updated data is not there, then look at your server's "save" logic, as it would appear to be failing.
If it is there, then you should look at your client's "retrieve" logic. I wonder, for example, if your app is caching the responses to its requests, and thus when you attempt to download again, perhaps you're getting the cached original response. I'd try turning off caching.
In these cases, a tool like Charles can be useful, where you can inspect the requests and responses that you're getting. That can be helpful in narrowing down precisely where the problem is occurring.
Taking a closer look at your request, I notice that you're not specifying the request type. I would have thought that your request would be a POST:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"]; // I'd also personally set the `Accept` here at the request, not at the `NSURLSessionConfiguration`
Having said that, given that your web service is successfully reporting your plist data back at you, I would have inferred that it successfully received it on the basis of the evidence you shared with us thus far. But maybe the failure to make the request a POST request means that the web service concluded it didn't need to save anything.
Generally, when interfacing with a web service, rather than tweaking the request, like I have above, I'd encourage you to post data using one of the standard AFHTTPSessionManager variations of the POST method (one is for multipart/form-data requests, the other is for other requests). But I can't figure out what your server is doing on the basis of what you've provided thus far (e.g. it makes no sense that the server is sending the body of your request back to you at all; it makes no sense that the server would appear to have received your request, but doesn't do anything with it and doesn't report some error; etc.). So maybe try making the request a POST request and see if that fixes it. If not, run Charles on your old ASIHTTP source code, and you'll see precisely what the old request looks like and you should be able to reproduce it with AFNetworking.
I am using a NSBlockOperation in which i am trying to downlaod an audio file from server & storing it in documents directory.
NSBlockOperation *audioOperation = [NSBlockOperation blockOperationWithBlock:^{
//Perform doanload
NSString *itemStoredPath = [self downloadPOIAudioByUrl:itemUrl itemName:itemName folderName:itemFolder iteInfo:cacheAudioDetails];
// Update database
.....
}];
-(NSString *)downloadPOIAudioByUrl:(NSString *)itemUrl itemName:(NSString *)itemName folderName:(NSString *)folderName iteInfo:(CacheAudioDetails *)itemInfo {
// Get the url for video upload
NSURL *audioUrl = [NSURL URLWithString:[itemUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// Set the response parameter
NSURLResponse *serverResponce = nil;
// Set the error parameter
NSError *error = nil;
// Create a request & set the time out interval for 1 min.
//NSURLRequest *videoRequest = [NSURLRequest requestWithURL:videoUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
NSURLRequest *audioRequest = [NSURLRequest requestWithURL:audioUrl];
// Set the connection
NSData *audioData = [NSURLConnection sendSynchronousRequest:audioRequest returningResponse:&serverResponce error:&error];
if (error == nil && audioData != nil) {
// Data Found
// Store in directory & return the path to store in database
return audioPath;
}
return nil;
}
I have made a synchronous call to downlaod an audio file. But it is taking too much time & after long time it returns zero bytes of NSData.I thought it was due to my timed out request for 60 sec. Then i removed the time out request but still the problem remains as it is. My query is
Time out is related to server connection & not to fetching data from server
What should be the reason of Zero bytes responce from server.
Here is the really simple call I make :
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:500];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection start];
I try with 2 random pdf urls found on google (searching "truc filetype:pdf") :
A) NSString *urlString = #"http://www.eatletruc.com/letruc.menu0411.pdf";
B) NSString *urlString = #"http://www.botruc.com/boat-specs/C-Truc-7.pdf";
They both have similar headers (using allHeaderFields in connection:didReceiveResponse:) :
A)
"Accept-Ranges" = bytes;
Connection = "Keep-Alive";
"Content-Length" = 2641705;
"Content-Type" = "application/pdf";
Date = "Thu, 11 Apr 2013 08:53:39 GMT";
Etag = "\"19a7b55-284f29-4a0a5e94ae1a7\"";
"Keep-Alive" = "timeout=5, max=100";
"Last-Modified" = "Mon, 11 Apr 2011 15:05:50 GMT";
Server = Apache;
B)
"Accept-Ranges" = bytes;
Connection = "Keep-Alive";
"Content-Length" = 343793;
"Content-Type" = "application/pdf";
Date = "Thu, 11 Apr 2013 08:55:38 GMT";
Etag = "\"b6864a-53ef1-49400c1d95800\"";
"Keep-Alive" = "timeout=5, max=100";
"Last-Modified" = "Mon, 01 Nov 2010 17:01:20 GMT";
Server = "Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635";
But connection:willCacheResponse: is only called for url B. And I find only url B in the Cache.db sqlite database.
Why isn't url A cached?
Ok, so the problem comes from the size of the file.
It seems that NSURLCache won't cache files that are bigger than 5% of the disk capacity it has.
My NSURLCache was set with 50MB of disk capacity, so files bigger than 2.5MB aren't cached.
Extending the disk capacity solved my problem.
ps : you can extend the disk capacity to 2GB max, so files in cache can't be bigger than 100MB.