Reputation: 8629
I am following a tutorial about Multithreading from http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial. In this tutorial ASIHTTPRequest is used and I see that AFNetworking has pretty much become the standard now.
I am trying to download a zip file using this block:
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:sourceURL];
[request setCompletionBlock:^{
NSLog(@"Zip file downloaded.");
NSData *data = [request responseData];
[self processZip:data sourceURL:sourceURL];
}];
How would I go about doing this in AFNetworking? Do I need to use something like this?
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
In the tutorial I need is to download as NSData though and in AFNetworking is is using NSURlResponse.
Any pointers on this would be great. thanks :)
Upvotes: 1
Views: 194
Reputation: 3326
The AFNetworking part looks right I suppose. Just try that out and see if it works. In order to retrieve the NSData of the downloaded file you could just use the contentsAtPath
method from NSFileManager
.
Example:
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
NSString *path = [filePath path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
}];
Upvotes: 1
Reputation: 2152
I would seriously go and look at Apple's documentation on NSURLSession. Before NSURLSession, configuring a simple upload/download task with NSURLConnection was a bit of a pain (to say the least), hence AFNetworking became very popular... and deservedly so.
But NSURLSession has fixed much of that and in general, it's a good idea to get to know the real API's versus a third party (and no disrespect intended towards AFNetworking).
The learning curve for NSURLSession has lowered so much that it is not much worse than learning AFNetworking... at least IMHO.
And to be more specific about your above question, I believe you only have to substitute the above AFURLSessionManager call with the equivalent NSURLSessionManager call.
Upvotes: 2