ios network ios networkmanager

admin2024-10-07  27

AFNetworking在3.0版本中删除了基于 NSURLConnection API的所有支持。AFHTTPRequestOperationManager已经抛弃,所以需要对数据请求进行改动。

Get请求

//使用代码
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        //成功
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //失败
    }];
  • 当我们调用get函数之前,我们需要创建一个AFHTTPSessionManager,在之前我们使用的一般是AFHTTPRequestOperationManager.

  • 在调用get请求后,我们一般都不需要干什么了,因为那些繁琐复杂的网络通信都交给他去做了,他首先会调用AFNetworkReachabilityManager验证是否联网.
  • 然后参数序列化,用于网络请求.
  • 调用AFSecurityPolicy类,AFSecurityPolicy用于验证HTTPS请求的证书,简单来说建立连接.
  • 连接建立完成,证书验证成功,开始请求服务器.
  • 从服务器返回数据,解析服务器数据,将数据反序列化.
  • 我们得到data类型的数据,可以使用JSON解析直接解析成字典使用.弃用的类:
  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager
  • 两者之间对比

AFN2.0:

NSURL *URL = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
  • AFN3.0:
NSURL *URL = [NSURL URLWithString:@""];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
<pre class="hljs objectivec"><code class="objectivec"><span >//如果报接受类型不一致请替换一致text/html或别的</span>
    manager<span >.responseSerializer</span><span >.acceptableContentTypes</span> = [<span >NSSet</span> setWithObject:<span >@"text/html"</span>];</code>
•   [manager GET:URL.absoluteString parameters:nil success:^(NSURLSessionTask *task, id responseObject) { NSLog(@"JSON: %@", responseObject);} failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Error: %@", error);}]
  • ; POST请求:
<span style="font-family:Microsoft YaHei;font-size:14px;">AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSMutableDictionary *parameters = @{@"":@"",@"":@""};
</span><pre class="hljs objectivec"><code class="objectivec"><span >//如果报接受类型不一致请替换一致text/html或别的</span>
    manager<span >.responseSerializer</span><span >.acceptableContentTypes</span> = [<span >NSSet</span> setWithObject:<span >@"text/html"</span>];</code>
•   [manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
 } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {}];

AFN3.0下载方法:

/**
 *  AFN3.0 下载
 */
- (void)downLoad{

    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.确定请求的URL地址
    NSURL *url = [NSURL URLWithString:@""
//如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

        //下载完成调用的方法
        WKNSLog(@"下载完成:");
        WKNSLog(@"%@--%@",response,filePath);

    }];

    //开始启动任务
    [task resume];

}
- (void)AFNetworkStatus{

    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];

    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
         AFNetworkReachabilityStatusUnknown          = -1,      未知
         AFNetworkReachabilityStatusNotReachable     = 0,       无网络
         AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
         AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */

    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                WKNSLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                WKNSLog(@"无网络");
                break;

            case AFNetworkReachabilityStatusReachableViaWWAN:
                WKNSLog(@"蜂窝数据网");
break;

            case AFNetworkReachabilityStatusReachableViaWiFi:
                WKNSLog(@"WiFi网络");

                break;

            default:
                break;
        }

    }] ;
}

AFN3.0 上传

/**
 *  AFN 3.0 上传
 *      有两种方式
 *          upLoad1 和 upLoad2
 */

//第一种方法是通过工程中的文件进行上传
- (void)upLoad1{

    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //2.上传文件
    NSDictionary *dict = @{@"username":@"1234"};

    NSString *urlString = @"22222";
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        UIImage *iamge = [UIImage imageNamed:@"123.png"];
        NSData *data = UIImagePNGRepresentation(iamge);
        //这个就是参数
        [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
//打印下上传进度
        WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        //请求成功
        WKNSLog(@"请求成功:%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        //请求失败
        WKNSLog(@"请求失败:%@",error);
    }];

}
//第二种是通过URL来获取路径,进入沙盒或者系统相册等等
- (void)upLoda2{
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.上传文件
    NSDictionary *dict = @{@"username":@"1234"};

    NSString *urlString = @"22222";
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

        //打印下上传进度
        WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        //请求成功
        WKNSLog(@"请求成功:%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        //请求失败
        WKNSLog(@"请求失败:%@",error);
    }];
}


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!