iOS 使用AFNetworking进行下载和上传

来源:互联网 发布:淘宝女装描述模板 编辑:程序博客网 时间:2024/06/11 16:32

AFNetworking为我们提供了太多的方便,今天说一下用AFNetworking进行文件的下载和上传,AFNetworking的引入就不多说了

首先,在storyboard的view上添加一个imageview和一个button,分别增加输出口和点击事件



ViewController.m中引入头文件#import<AFNetworking.h>

然后在button点击事件中加入下载方法

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];    NSURL *URL = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1504497234144&di=a3169e58078bb55ae38bfc99fd18f17e&imgtype=jpg&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8694a4c27d1ed21bd85def25a46eddc450da3f5e.jpg"];    NSURLRequest *request = [NSURLRequest requestWithURL:URL];        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){//        这个block里面获取下载进度        [SVProgressHUD showProgress:(CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount status:@"下载中"];    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {//        这个block里面返回下载文件存放路径        if([self isFileExist:[response suggestedFilename]]) {            NSLog(@"文件已存在");        }        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];//        [response suggestedFilename]为文件名        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];        return url;    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {//        这个block里面拿到下载结果        NSData *data = [NSData dataWithContentsOfURL:filePath];        UIImage *img = [UIImage imageWithData:data];        self.imageView.image = img;                [SVProgressHUD dismissWithDelay:0.0 completion:nil];    }];    [downloadTask resume];


判断将要下载文件是否已存在

//判断文件是否已经在沙盒中存在-(BOOL) isFileExist:(NSString *)fileName{    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *path = [paths objectAtIndex:0];    NSString *filePath = [path stringByAppendingPathComponent:fileName];    NSFileManager *fileManager = [NSFileManager defaultManager];    BOOL result = [fileManager fileExistsAtPath:filePath];    NSLog(@"这个文件已经存在:%@",result?@"是的":@"不存在");    return result;}

上传,因为没有服务器,就只能把自己用过的方法写下来,希望能对需要的朋友有所帮助

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];        [manager POST:@"https://pan.baidu.com/disk/home#list/vmode=list&path=%2Fsz" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];        //        self.fileName为要上传文件的文件名        NSURL *filePath = [documentsDirectoryURL URLByAppendingPathComponent:self.fileName];        //上传        /*         此方法参数         1. 要上传的data数据         2. 后台处理文件的字段,若没有可为空         3. 要保存在服务器上的[文件名]         4. 上传文件的[mimeType]         application/octet-stream为通用型         *///        [formData appendPartWithFileData:fileData name:@"file" fileName:self.fileName mimeType:@"application/octet-stream"];                /*         此方法参数         1. 要上传的文件路径         2. 后台处理文件的字段,若没有可为空         3. 要保存在服务器上的[文件名]         4. 上传文件的[mimeType]         application/octet-stream为通用型         */        [formData appendPartWithFileURL:filePath name:@"file" fileName:self.fileName mimeType:@"application/octet-stream" error:nil];        //个人比较建议用第二种,传文件路径,因为自己做上传当时的场景是把wps编辑后的文档上传到服务器,因为回传回来的是一个字典,我就直接将字典内容解析出来转成data数据,但是上传到服务器后文档打开时提示文件损坏,下载下来打开是乱码,推测应该是wps回传回来的数据里应该有自己的一些编码在里面,导致直接上传data数据会出现后台解析错误的问题,后来把回传回来的数据转成文件之后,再用文件路径方法上传就没问题了。    } progress:^(NSProgress * _Nonnull uploadProgress) {            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {        [SVProgressHUD showSuccessWithStatus:@"上传成功"];            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {        [SVProgressHUD showErrorWithStatus:@"上传失败"];    }];

上面的上传地址是我自己的百度云盘,虽然没报错,但是没上传到云盘里,只是作为示范。

demo下载地址