AFNetworking 2.0使用(持续更新)

简介:

本人视频教程系列

 

导入AFNetworking 2.0 文件夹,引入头文件AFNetworking.h

---------------

*使用NSURLSessionDownloadTask来下载一张图片,并带有下载进度(以下两段代码是一起的,注意)

NSProgress为iOS7新增加的类


// 定义一个progress指针
    NSProgress *progress;
    
    // 创建一个URL链接
    NSURL *url = [NSURL URLWithString:\
                  @"http://wallpapers.wallbase.cc/rozne/wallpaper-3020771.jpg"];
    
    // 初始化一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 获取一个Session管理器
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    // 开始下载任务
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
    {
        // 拼接一个文件夹路径
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        // 根据网址信息拼接成一个完整的文件存储路径并返回给block
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
    {
        // 结束后移除掉这个progress
        [progress removeObserver:self
                      forKeyPath:@"fractionCompleted"
                         context:NULL];
    }];
    
    // 设置这个progress的唯一标示符
    [progress setUserInfoObject:@"someThing" forKey:@"Y.X."];
    [downloadTask resume];
    
    // 给这个progress添加监听任务
    [progress addObserver:self
               forKeyPath:@"fractionCompleted"
                  options:NSKeyValueObservingOptionNew
                  context:NULL];


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        NSLog(@"Progress is %f", progress.fractionCompleted);
        
        // 打印这个唯一标示符
        NSLog(@"%@", progress.userInfo);
    }
}

*使用AFHTTPRequestOperation下载图片的操作,不过,没有进度显示(源码中也没有相关方法-_-!)
// 组织一个请求
    NSURLRequest *request = \
    [NSURLRequest requestWithURL:\
     [NSURL URLWithString:@"http://images.cnitblog.com/i/607542/201404/050759358125578.png"]];
    
    // 建立请求操作
    AFHTTPRequestOperation *requestOperation = \
    [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    // 进行操作的配置(下载图片,还有其他的类型)
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    
    // 设置获取数据的block
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 源码中为并发线程池返回了主线程
         NSLog(@"Response: %@", responseObject);
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         // 源码中为并发线程池返回了主线程
         NSLog(@"Image error: %@", error);
     }];
    
    // 开始执行
    [requestOperation start];

*下载队列,且能在后台下载,关闭了应用后还继续下载(这个功能好^_^)

Upload and download tasks in background sessions are performed by an external daemon instead of by the app itself. As a result, the transfers continue in the background even if the app is suspended, exits, or crashes.

在后台进行上传或者下载任务的会话,是被系统的程序管理而不是应用本身来管理的.所以呢,当app挂了,推出了甚至崩溃了,这个下载还是继续着的

@interface DownloadsViewController ()

{
    AFURLSessionManager *manager;
}

@end


// 配置后台下载会话配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"];
    
    // 初始化SessionManager管理器
    manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    // 获取添加到该SessionManager管理器中的下载任务
    NSArray *downloadTasks = [manager downloadTasks];
    
    // 如果有下载任务
    if (downloadTasks.count)
    {
        NSLog(@"downloadTasks: %@", downloadTasks);

        // 继续全部的下载链接
        for (NSURLSessionDownloadTask *downloadTask in downloadTasks)
        {
            [downloadTask resume];
        }
    }

按按钮添加一个下载任务到manager中
- (void)addDownloadTask:(id)sender
{
    // 组织URL
    NSURL *URL = [NSURL URLWithString:@"http://pic.cnitblog.com/avatar/607542/20140226182241.png"];
    
    // 组织请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // 给SessionManager管理器添加一个下载任务
    NSURLSessionDownloadTask *downloadTask = \
    [manager downloadTaskWithRequest:request
                            progress:nil
                         destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                             NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
                             return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
                         } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                             NSLog(@"File downloaded to: %@", filePath);
                         }];
    [downloadTask resume];
    
    // 打印下载的标示
    NSLog(@"%d", downloadTask.taskIdentifier);
}




目录
相关文章
|
11月前
|
Go Android开发
AS常用插件-持续更新
AS常用插件-持续更新
116 0
|
程序员 开发工具 数据安全/隐私保护
GitHub使用方法(扫盲)
GitHub使用方法(扫盲)
200 0
GitHub使用方法(扫盲)
|
网络安全 开发工具 数据安全/隐私保护
版本控制神器GitHub的基本使用与踩坑,教你一铲子填平!
![](https://ceshiren.com/uploads/default/original/3X/5/7/577bcc2d8a6d08b63c42c9cf7d62a83d7dec13ea.gif) ![](https://ceshiren.com/uploads/default/original/3X/c/3/c3193661cc0c2d46655f391bf7db03c55ca6ee6
|
网络安全 开发工具 数据安全/隐私保护
版本控制神器GitHub的基本使用与踩坑
首先需要申请GitHub帐号,这个就不多说了,大家自行百度或Google吧哈。这里默认大家都已经有GitHub账号了~
|
缓存 安全
AFNetworking 源码探究
1. AFNetworking源码探究(一) —— 基本介绍2. AFNetworking源码探究(二) —— GET请求实现之NSURLSessionDataTask实例化(一)3.
1531 0
|
缓存 安全
AFNetworking源码探究
AFNetworking源码探究(一) —— 基本介绍AFNetworking源码探究(二) —— GET请求实现之NSURLSessionDataTask实例化(一)AFNetworking源码探究(三) —— GET请求实现之任务进度设置和通知监听...
941 0
|
Kotlin
《Kotlin极简教程》 勘误 issue 2017.9.16
《Kotlin极简教程》 勘误 issue 2017.9.16 correct_errors_of_easykotlin_book 1316117604.
902 0