AFNetwork的使用

</pre><pre name="code" class="objc">// 网络请求
- (void)requestWithURL:(NSString *)url
             parameter:(NSDictionary *)paraDic
               success:(void(^)(id obj))success
                  fail:(void(^)(NSError *error))fail
{
    // NSURLSession 配置信息
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    // 创建请求
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paraDic constructingBodyWithBlock:nil error:nil];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error)
        {
            fail(error);
        }
        else
        {
            success(responseObject);
        }
    }];
    
    // 开启任务
    [dataTask resume];
}

// 文件上传
- (void)uploadWithURL:(NSString *)url
                image:(UIImage *)image
            parameter:(NSDictionary *)paraDic
              success:(void (^)(id obj))success
                 fail:(void (^)(NSError *error))fail
{
    // NSURLSession 配置信息
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    // 创建请求
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /*
        在这里提交图片/视频/音频文件
        把图片转为NSData
        第一个参数是 data
        第二个参数是服务器提供的字段名, 片刻里是 iconfile
        第三个字段随意
        第四个参数文件类型
        */
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        NSString *fileName = [NSString stringWithFormat:@"%f.png", [[NSDate date] timeIntervalSince1970]];
        [formData appendPartWithFileData:data name:@"iconfile" fileName:fileName mimeType:@"PNG/JPEG/JPG"];
    } error:nil];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error)
        {
            fail(error);
        }
        else
        {
            success(responseObject);
        }
    }];
    
    // 开启任务
    [dataTask resume];
}

// 下载
// progressBlock 下载进度
// completeBlock 成功回调
- (void)downloadWithURL:(NSString *)url
               progress:(void (^)(float percent))precentBlock
               complete:(void (^)(NSString *fileName))completeBlock
                fileUrl:(void(^)(NSURL *fileUrl))fileUrl
{
    // 在cache文件下, 创建存储MP3文件的的文件夹
    // 建立存储路径/Download
    NSString *mp3FilePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Download"];
    // 判断文件夹是否存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:mp3FilePath])
    {
        
    }
    else
    {
        // 创建文件夹
        [fileManager createDirectoryAtPath:mp3FilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *fileName = url.md5;
    // 文件下载成功后存储路径
    NSString *filePath = [mp3FilePath stringByAppendingPathComponent:fileName];
    // 如果文件已下载, 停止下载
    if ([fileManager fileExistsAtPath:filePath])
    {
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"文件已下载" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        
        return;
    }
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    // 创建request
    // POST请求, 用 [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:]
    
    // 如果是GET请求, 用下面的方法
    NSURL *urlRequest = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlRequest];
    // 创建下载任务
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里返回下载进度
        dispatch_async(dispatch_get_main_queue(), ^{
            precentBlock(downloadProgress.completedUnitCount / (downloadProgress.totalUnitCount / 1.0));
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 要求返回文件存储的路径
        // 临时文件
        NSString *tempPath = NSTemporaryDirectory();
        NSURL *urlPath = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", tempPath, fileName]];
        return urlPath;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePt, NSError * _Nullable error) {
        // 下载完成
        if (!error)
        {
            /*
            先把临时文件移到download文件夹
            然后删除临时文件
            成功回调
            */
            [fileManager copyItemAtURL:filePt toURL:[NSURL fileURLWithPath:filePath] error:nil];
            [fileManager removeItemAtURL:filePt error:nil];
            completeBlock(fileName);
        }
        else
        {
            [[[UIAlertView alloc] initWithTitle:@"提示" message:@"网络请求失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        }
    }];
    
    [task resume];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值