IOS分别利用NSURLSession和AFNetworking实现下载文件,有需要的朋友可以参考下。
NSURLRequest *request = [NSURLRequest requestWithURL:_imageUrl]; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler: ^(NSURL *location, NSURLResponse *response, NSError *error) { UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]]; dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; }); }]; [task resume];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration]; NSURLRequest *request = [NSURLRequest requestWithURL:_imageUrl]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) { NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error) { //此处已经在主线程了 UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]]; self.imageView.image = image; }]; [downloadTask resume];不管用哪种方法最后一定要执行 task 的 resume方法 因为默认下载操作是挂起的,必须先手动恢复下载。
联系客服