当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS 【network-封装业务类AFNetworking(AFHTTPSessionManager)】

iOS 【network-封装业务类AFNetworking(AFHTTPSessionManager)】

2018年12月26日  | 移动技术网IT编程  | 我要评论

石瘕膏,濠江岁月国语,天师鬼禄

由于afnetworking底层请求由nsurlconnection更新为nsurlsession,管理者对象也由afhttprequestoperationmanager更新为afurlsessionmanager。

本文重点讲述如何封装afn业务类,将第三方为程序带来的污染减小到最低。

 

代码描述:

① 封装业务类

//
//  wzyafntool.h
//  0716-02afn上传下载getpost-01
//
//  created by 王中尧 on 16/7/16.
//  copyright © 2016年 wzy. all rights reserved.
//

#import 
@class afnetworking;

@interface wzyafntool : nsobject

+ (void)get:(nsstring *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(nserror *error))failure;

+ (void)post:(nsstring *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(nserror *error))failure;

+ (void)unload:(nsstring *)uploadurl parameters:(id)params filepath:(nsstring *)filepath name:(nsstring *)name progress:(void (^)(nsprogress *))progress success:(void (^)(id object))success failure:(void (^)(nserror *))failure;

+ (void)download:(nsstring *)url progress:(void (^)(nsprogress *progress))progress destination:(nsurl *(^)(nsurl *targetpath, nsurlresponse *response))destination failure:(void (^)(nsurlresponse * response, nsurl * filepath, nserror * error))failure;

@end

//
//  wzyafntool.m
//  0716-02afn上传下载getpost-01
//
//  created by 王中尧 on 16/7/16.
//  copyright © 2016年 wzy. all rights reserved.
//

#import "wzyafntool.h"
#import "afnetworking.h"

@implementation wzyafntool

+ (void)get:(nsstring *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(nserror *error))failure {
    
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    [manager get:url parameters:params progress:nil success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        if (success) {
            success(responseobject);
        }
        
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
       
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)post:(nsstring *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(nserror *error))failure {
    
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    [manager get:url parameters:params progress:nil success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        if (success) {
            success(responseobject);
        }
        
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)unload:(nsstring *)uploadurl parameters:(id)params filepath:(nsstring *)filepath name:(nsstring *)name progress:(void (^)(nsprogress *progress))progress success:(void (^)(id object))success failure:(void (^)(nserror *error))failure {
    
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];

    [manager post:uploadurl parameters:params constructingbodywithblock:^(id  _nonnull formdata) {
        
        /*
         第一个参数:要上传的文件的url
         第二个参数:后台接口规定
         第三个参数:错误信息
         */
        [formdata appendpartwithfileurl:[nsurl fileurlwithpath:filepath] name:name error:nil];
    } progress:^(nsprogress * _nonnull uploadprogress) {
        
        if (progress) {
            progress(uploadprogress);
        }
        
    } success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        if (success) {
            success(responseobject);
        }
        
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)download:(nsstring *)url progress:(void (^)(nsprogress *progress))progress destination:(nsurl *(^)(nsurl *targetpath, nsurlresponse *response))destination failure:(void (^)(nsurlresponse * response, nsurl * filepath, nserror * error))failure {
    // 1 创建会话管理者
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    // 2 创建请求路径 请求对象
    nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:url]];
    
    // 3 创建请求下载操作对象
    nsurlsessiondownloadtask *downtask = [manager downloadtaskwithrequest:request progress:^(nsprogress * _nonnull downloadprogress) {
        
        if (progress) {
            progress(downloadprogress);
        }
        
    } destination:^nsurl * _nonnull(nsurl * _nonnull targetpath, nsurlresponse * _nonnull response) {
        
        if (destination) {
            return  destination(targetpath, response);
        } else {
            return nil;
        }
    } completionhandler:^(nsurlresponse * _nonnull response, nsurl * _nullable filepath, nserror * _nullable error) {
        if (failure) {
            failure(response, filepath, error);
        }
    }];
    
    // 4 执行任务发送下载操作请求
    [downtask resume];
}

@end

 

② 调用

 

//
//  viewcontroller.m
//  0716-02afn上传下载getpost-01
//
//  created by 王中尧 on 16/7/16.
//  copyright © 2016年 wzy. all rights reserved.
//

#import "viewcontroller.h"
#import "afnetworking.h"

#import "wzyafntool.h"

@interface viewcontroller ()

@end

@implementation viewcontroller

- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event {
    // 使用afn原生方法
//    [self getafn];
//    [self postafn];
//    [self upload];
//    [self download];
    
    // 使用wzyafntool业务类
//    [self wzyget];
//    [self wzypost];
//    [self wzyupload];
//    [self wzydownload];
}

// afn get请求
- (void)getafn {
    
    // 1 封装会话管理者
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    // 2 拼接请求参数
    nsdictionary *dict = @{
                           @"username" : @"520it",
                           @"pwd" : @"520it",
                           @"type" : @"json"
                           };
    // 3 发送请求
    /*
     第一个参数:请求路径(!不包含参数) 类型是nsstring
     以前:https://120.25.226.186:32812/login?username=520it&pwd=123&type=json
     现在:https://120.25.226.186:32812/login
     第二个参数:参数(用字典来保存参数)
     第三个参数:progress 进度回调
     第四个参数:success成功之后的回调
     responseobject:注意此参数是响应体(内部已经完成了反序列化处理:json--->oc,此处类型为id,也就是oc对象)
     task.response:响应头
     第五个参数:failure 失败之后的回调
    */
    [manager get:@"https://120.25.226.186:32812/login" parameters:dict progress:nil success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        nslog(@"success---%@---%@", responseobject, [responseobject class]);
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
        nslog(@"failure---%@", error);
    }];
    
}
// wzyafntool get请求
- (void)wzyget {
    nsdictionary *dict = @{
                           @"username" : @"520it",
                           @"pwd" : @"520it",
                           @"type" : @"json"
                           };
    
    [wzyafntool get:@"https://120.25.226.186:32812/login" parameters:dict success:^(id object) {
        nslog(@"success---%@", object);
    } failure:^(nserror *error) {
        nslog(@"error---%@", error);
    }];
}


// afn post请求
- (void)postafn {
    // 1 封装会话管理者
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    // 2 拼接请求参数
    nsdictionary *dict = @{
                           @"username" : @"520it",
                           @"pwd" : @"520it",
                           @"type" : @"json"
                           };
    // 3 发送请求
    /*
     第一个参数:请求路径(!不包含参数) 类型是nsstring
     以前:https://120.25.226.186:32812/login?username=520it&pwd=123&type=json
     现在:https://120.25.226.186:32812/login
     第二个参数:参数(用字典来保存参数)
     第三个参数:progress 进度回调
     第四个参数:success成功之后的回调
     responseobject:注意此参数是响应体(内部已经完成了反序列化处理:json--->oc,此处类型为id,也就是oc对象)
     task.response:响应头
     第五个参数:failure 失败之后的回调
     */
    [manager post:@"https://120.25.226.186:32812/login" parameters:dict progress:nil success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        nslog(@"success---%@---%@", responseobject, [responseobject class]);
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
        nslog(@"failure---%@", error);
    }];
}
// wzyafntool post请求
- (void)wzypost {
    nsdictionary *dict = @{
                           @"username" : @"520it",
                           @"pwd" : @"520it",
                           @"type" : @"json"
                           };
    [wzyafntool post:@"https://120.25.226.186:32812/login" parameters:dict success:^(id object) {
        nslog(@"success---%@", object);
    } failure:^(nserror *error) {
        nslog(@"error---%@", error);
    }];
}


// afn 上传
- (void)upload {
    // 1 创建请求者对象
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    // 2 发送post请求上传数据文件
    nsdictionary *dict = @{@"wzy" : @"wangzhongyao"};
    
    /*
     第一个参数: 请求路径
     第二个参数: 非文件参数 (字典)
     第三个参数: constructingbodywithblock 处理上传的文件
     第四个参数: progress 进度回调
     第五个参数: success 成功之后的回调
     responseobject 响应体
     第六个参数: failure 失败之后的回调
     */
    
    [manager post:@"https://120.25.226.186:32812/upload" parameters:dict constructingbodywithblock:^(id  _nonnull formdata) {
        
        /*
         第一个参数:要上传的文件的url
         第二个参数:后台接口规定
         第三个参数:错误信息
         */
        [formdata appendpartwithfileurl:[nsurl fileurlwithpath:@"/users/wangzhongyao/desktop/snip20160716_17.png"] name:@"file" error:nil];
    } progress:^(nsprogress * _nonnull uploadprogress) {
        
        // 上传进度
        nslog(@"unload --- %f", 1.0 *uploadprogress.completedunitcount / uploadprogress.totalunitcount);
        
    } success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        
        //json--->oc 反序列化
        nslog(@"响应体 --- %@",responseobject); // responseobject 响应体 在方法内部就反序列化成功
    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
        
        // 输出错误信息
        nslog(@"%@", error);
    }];
}
// wzyafntool 上传
- (void)wzyupload {
    nsdictionary *dict = @{@"wzy" : @"wangzhongyao"};
    
    [wzyafntool unload:@"https://120.25.226.186:32812/upload" parameters:dict filepath:@"/users/wangzhongyao/desktop/snip20160716_17.png" name:@"file" progress:^(nsprogress *progress) {
        
        // 上传进度
        nslog(@"unload --- %f", 1.0 *progress.completedunitcount / progress.totalunitcount);
    } success:^(id object) {
        
        //json--->oc 反序列化
        nslog(@"响应体 --- %@",object); // responseobject 响应体 在方法内部就反序列化成功
    } failure:^(nserror *error) {
        
        // 输出错误信息
        nslog(@"%@", error);
    }];
    
}


// afn 下载
- (void)download {
    
    /*
     第一个参数: 请求对象
     第二个参数: progress进度回调
     第三个参数: destination url处理的回调
               targetpath:文件下载到沙盒中的临时路径
               response:响应头信息
     返回值: 告诉afn文件应该剪切到什么地方
     第四个参数: completionhandler完成之后的回调
               filepath:就是文件的最终保存位置
     */
    
    // 1 创建会话管理者
    afhttpsessionmanager *manager = [afhttpsessionmanager manager];
    
    // 2 创建请求路径 请求对象
    nsurl *url = [nsurl urlwithstring:@"https://www.bz55.com/uploads/allimg/150326/140-150326141213-50.jpg"];
    nsurlrequest *request = [nsurlrequest requestwithurl:url];
   
    // 3 创建请求下载操作对象
    nsurlsessiondownloadtask *downtask = [manager downloadtaskwithrequest:request progress:^(nsprogress * _nonnull downloadprogress) {
        
        // 计算进度
        nslog(@"downloading --- %f", 1.0 * downloadprogress.completedunitcount / downloadprogress.totalunitcount);
        
    } destination:^nsurl * _nonnull(nsurl * _nonnull targetpath, nsurlresponse * _nonnull response) {
        
        // 获得文件下载保存的全路径
        nsstring *fullpath = [[nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) lastobject] stringbyappendingpathcomponent:response.suggestedfilename];
        nslog(@"fullpath --- %@, tmppath --- %@", fullpath, targetpath); // 打印需要修改的全路径 & 临时路径
        
        // 该方法会拼接上协议头 file:// 成为一个完整的url,而urlwithstring不会自动拼接协议头
        return [nsurl fileurlwithpath:fullpath]; // 该block是有返回值的,返回文件剪切保存的路径
        
    } completionhandler:^(nsurlresponse * _nonnull response, nsurl * _nullable filepath, nserror * _nullable error) {
        nslog(@"filepath --- %@", filepath);
    }];
    
    // 4 执行任务发送下载操作请求
    [downtask resume];
}
// wzyafntool 下载
- (void)wzydownload {
    [wzyafntool download:@"https://www.bz55.com/uploads/allimg/150326/140-150326141213-50.jpg" progress:^(nsprogress *progress) {
        
        // 计算进度
        nslog(@"downloading --- %f", 1.0 * progress.completedunitcount / progress.totalunitcount);
        
    } destination:^nsurl *(nsurl *targetpath, nsurlresponse *response) {
        
        // 获得文件下载保存的全路径
        nsstring *fullpath = [[nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) lastobject] stringbyappendingpathcomponent:response.suggestedfilename];
        nslog(@"fullpath --- %@, tmppath --- %@", fullpath, targetpath); // 打印需要修改的全路径 & 临时路径
        
        // 该方法会拼接上协议头 file:// 成为一个完整的url,而urlwithstring不会自动拼接协议头
        return [nsurl fileurlwithpath:fullpath];
        
    } failure:^(nsurlresponse *response, nsurl *filepath, nserror *error) {
        
        nslog(@"filepath --- %@", filepath); // filepath --- (null)
        
    }];
}

@end

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

  • ios uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网