https://github.com/YouXianMing

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:@"//images0.cnblogs.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);
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2014-04-08 10:41  YouXianMing  阅读(5286)  评论(11编辑  收藏  举报