现在的位置: 首页 > 综合 > 正文

AFNetworking断点续传、下载图片和json等文件

2018年08月04日 ⁄ 综合 ⁄ 共 4929字 ⁄ 字号 评论关闭

ASI早就不更新了,直接导入在ios7就有很多错误,大家也都偏向了AFNetworking等其他的网络框架。

具体的文档可以参考https://github.com/AFNetworking/AFNetworking/

下载图片:下载图片后保存在本地文件中

    //在lock和挂起状态都会下载
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://attach.bbs.miui.com/forum/201110/05/082552rm0v11zlv1axd13l.png"]];
    //操作配置
    AFHTTPRequestOperation *requestOperator=[[AFHTTPRequestOperation alloc]initWithRequest:request];
    requestOperator.responseSerializer=[AFImageResponseSerializer serializer];
    [requestOperator setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //主线程中执行
        self.pictureView.image=responseObject;
        NSString *fileDestination=[NSHomeDirectory() stringByAppendingString:@"/Documents/1.png"];
        <span style="color:#ff6666;">//若respondObject为NSData,则用下面的方法</span>
        /*NSFileManager *fileManage=[NSFileManager defaultManager];
        if([fileManage createFileAtPath:fileDestination contents:imgData attributes:nil]){
            NSLog(@"%@",fileDestination);
        }*/
        if([UIImageJPEGRepresentation(responseObject, 1.0) writeToFile:fileDestination atomically:YES]){
            //成功后运行
            NSLog(@"%@",fileDestination);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"error:%@",error);
    }];
    //监听下载进度
    [requestOperator setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
        self.progressView.progress=totalBytesRead*1.0/totalBytesExpectedToRead;
        //NSLog(@"%.3f",totalBytesRead*1.0/totalBytesExpectedToRead);
    }];
    //开始执行
    [requestOperator start];

下载json文件这里列出了2中方法:

这种就是nsdata数据 用自带的json解析就可以了

    //----------------------------------------------------第一种json--------------
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://fm.baidu.com/dev/api/?tn=playlist&special=flash&prepend=&format=json&_=1378945264366&id=10101"]];
    //请求操作
    AFHTTPRequestOperation *requestOperator=[[AFHTTPRequestOperation alloc]initWithRequest:request];
    //操作配置
    //requestOperator.responseSerializer=[AFImageResponseSerializer serializer];
    [requestOperator setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //主线程中执行
        NSDictionary *dict=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSArray *list=dict[@"list"];
        for (NSDictionary *arrDict in list) {
            NSLog(@"%@",arrDict[@"id"]);
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Run Error:%@",error);
    }];
    //开始执行
    [requestOperator start];

第二种方法必须content-type必须规范application/json,对服务器端的数据meta的要求比较多,不过可以指定可接受的meta的content-type来读取数据,防止获取失败

    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://gitcafe.com/wcrane/XXXYYY/raw/master/baidu.json"]];
    //请求操作
    AFHTTPRequestOperation *requestOperator=[[AFHTTPRequestOperation alloc]initWithRequest:request];
    requestOperator.responseSerializer=[AFJSONResponseSerializer serializer];
    <span style="color:#ff6666;">//如果服务器沒把head內的 meta的content格式指定好,就必须自己设置可接受的格式和服务器一样</span>
    //requestOperator.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/plain"];
    requestOperator.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",nil];
    [requestOperator setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //主线程中执行
        //NSLog(@"%@",responseObject);
        NSArray *arr=responseObject;
        for (NSDictionary *arrDict in arr ){
            NSLog(@"title:%@",arrDict[@"title"]);
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Run Error:%@",error);
    }];
        //开始执行
    [requestOperator start];

断点续传:暂停和开始下载的按钮我都是一个按钮,所以定义了AFHTTPRequestOperation *resumeOperation和一个BOOL类型的resume判断是否续传。

因为在block中又调用了self,会造成内存泄露,所以定义了__weak的weakSelf解决内存泄露的问题

<span style="color:#ff0000;">__weak ViewController *weakSelf=self;</span>
    
    if(!self.resumeOperation){
        NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://attach.bbs.miui.com/forum/201110/05/082552rm0v11zlv1axd13l.png"]];
        self.resumeOperation=[[AFHTTPRequestOperation alloc]initWithRequest:request];
        self.resumeOperation.responseSerializer=[AFImageResponseSerializer serializer];
        [weakSelf.resumeOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
            //主线程中执行
            self.pictureView.image=responseObject;
            //保存文件
            NSString *fileDestination=[NSHomeDirectory() stringByAppendingString:@"/Documents/1.png"];
            if([UIImageJPEGRepresentation(responseObject, 1.0) writeToFile:fileDestination atomically:YES]){
                NSLog(@"%@",fileDestination);
            }
            self.resumeOperation=nil;
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error){
            self.resumeOperation=nil;
            NSLog(@"error:%@",error);
        }];
        //监听下载进度
        [weakSelf.resumeOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
            self.progressView.progress=totalBytesRead*1.0/totalBytesExpectedToRead;
            //NSLog(@"%.3f",totalBytesRead*1.0/totalBytesExpectedToRead);
        }];
        //开始执行
        [self.resumeOperation start];
    }else if(!self.resume){
        [self.resumeOperation pause];
        self.resume=YES;
    }else{
        //继续
        [self.resumeOperation resume];
        self.resume=NO;
    }

抱歉!评论已关闭.