美文网首页iOS收藏
iOS 网络请求/数据获取/图片上传及加载/多线程加载图片/数据

iOS 网络请求/数据获取/图片上传及加载/多线程加载图片/数据

作者: 爬树的蚂蚁 | 来源:发表于2017-01-20 15:50 被阅读320次

    前言

    1.网络请求

    系统请求的方法

    分为get请求和post请求
    1.1、get请求系统提供了两种方法,一种是Request方式的,一种是URL方式的。下面先说request方式的

    NSString * urlStr = @"http://172.16.101.125:8080/wisdombus-controller/mobile/class/queryBusLineList?corpId=0";
    NSURL * url = [NSURL URLWithString:urlStr];
    NSURLSession * senssion = [NSURLSession sharedSession];//网络请求管理者
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];//创建请求对象
    //创建网络数据请求任务的对象
    NSURLSessionDataTask * task1 = [senssion dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //由NSData对象获取json字符串
            NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",string);
            //NSData数据转字典
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",dic);
            //回到主线程
            [self performSelector:@selector(actionWithString:) onThread:[NSThread mainThread] withObject:string waitUntilDone:YES];
        }];
    [task1 resume];
    

    get请求url方式

    NSString * urlStr = @"http://172.16.101.125:8080/wisdombus-controller/mobile/class/queryBusLineList?corpId=0";
    NSURL * url = [NSURL URLWithString:urlStr];
    //网络请求管理者
    NSURLSession * senssion = [NSURLSession sharedSession];
    //创建网络数据请求任务的对象
    NSURLSessionDataTask * task2 = [senssion dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //获取json字符串
            NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",string);
        }];
    [task2 resume];
    

    1.2、post请求

    NSString * urlStr = @"http://172.16.101.125:8080/wisdombus-controller/mobile/class/queryBusLineList";
    NSURL * url = [NSURL URLWithString:urlStr];
    NSURLSession * senssion = [NSURLSession sharedSession];//网络请求管理者
    NSMutableURLRequest * Postrequest = [NSMutableURLRequest requestWithURL:url];
    Postrequest.HTTPMethod = @"POST";
        //设置包体
    Postrequest.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
        //创建任务
        NSURLSessionDataTask * task = [senssion dataTaskWithRequest:Postrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
            NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [self performSelector:@selector(actionWithString:) onThread:[NSThread mainThread] withObject:string waitUntilDone:YES];
        }];
    [task resume];
    
    第三方网络请求--AFNetWorking

    在使用网络请求的控制器中引入头文件

    #import <AFNetworking/AFNetworking.h>
    

    创建请求管理者,并设置相关属性

    //创建请求管理者
    AFHTTPSessionManager * sessionManager = [AFHTTPSessionManager manager];
    //上传设置
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];//普通格式上传
    //sessionManager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    sessionManager.requestSerializer.timeoutInterval = 10.0f;
    //返回数据设置
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];//自己动手解析
    //sessionManager.responseSerializer = [AFJSONResponseSerializer serializer]; // AFN会JSON解析返回的数据
    // 个人建议还是自己解析的比较好,有时接口返回的数据不合格会报3840错误,大致是AFN无法解析返回来的数据
    
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", @"text/html",@"charset=utf-8",  nil];
    //创建参数和参数值字典
    NSDictionary * dic = @{@"corpId":@"0"};
    NSString * urlString = @"http://172.16.101.125:8080/wisdombus-controller/mobile/class/queryBusLineList";
    

    post请求

    [sessionManager POST:urlString parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            self.textView2.text = [NSString stringWithFormat:@"%@",responseObject];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
    }];
    

    get请求

    [sessionManager GET:urlString parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            self.textView2.text = [NSString stringWithFormat:@"%@",responseObject];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
    }];
    

    注意:系统的网络请求的block中请求改变外部变量需要做特殊处理,但是第三方的不需要

    2.获取数据,并处理数据

    对于数据的处理主要是两种:
    一种是NSData转json字符串

    NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    

    一种是NSData数据转字典

    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    

    3.获取导数据后的非空处理

    对于获取到的数据,如果不做非空处理,很容易出现数组越界的情况。所以必须得处理,但是不同的后台开发人员,写的接口字段非空时返回的形式多种多样,所以要综合处理多种情况,才能避免出错。
    1、对于数组对象,需要判断元素的个数和数组是否为空

    if (self.busLineArr.count == 0||self.busLineArr == nil) {
            [self showErrorMessage:@"暂时不能进行切换"];
            return;
        }
    

    2、对于字符串对象,需要判断nil、NSNull对象、@“”、@“null”,等4种情况

    if (([str isKindOfClass:[NSNull class]]||str == nil||[[NSString stringWithFormat:@"%@",str] length] < 1||[[NSString stringWithFormat:@"%@",str] isEqualToString:@"(null)"])) {//字符串对象为空
     
    }else{//不为空
    
    }
    

    4.图片的上传

    图片上传格式比较固定

    NSError *error = nil;
    NSURLResponse *response = [NSURLResponse new];
    NSString *imageStr = @"http://172.16.101.125:8080/wisdombus-controller/mobile/auth/uploadIMG.do";
    NSURL *url = [NSURL URLWithString:imageStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方法
    [request setHTTPMethod:@"POST"];
    // 设置请求体
    [request setHTTPBody:_imageData];
    // 设置请求头的内容的类型
    [request setValue:[NSString stringWithFormat:@"cesi%.0f.png",[[NSDate date] timeIntervalSince1970]] forHTTPHeaderField:@"fileName"];//图片文件名字
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)_imageData.length] forHTTPHeaderField:@"fileSize"];//大小
    [request setValue:[NSString stringWithFormat:@"%@"[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"]] forHTTPHeaderField:@"userId"];//
    [request setValue:[NSString stringWithFormat:@"%d",2] forHTTPHeaderField:@"type"];
    NSString *contentType = [NSString stringWithFormat:@"Content-Type multipart/form-data; boundary=%@", kBoundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    // 发送异步请求
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (!error && responseData) {
      NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
         if ([[dic objectForKey:@"result"] isEqualToString:@"true"]) {
            //上传成功
         }else {
             //上传错误
         }
        }else if (error) {
          //操作失败
    }
    

    5.图片的下载问题

    图片加载影响主线程,所以要放到子线程中这里用GCD加载

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
         NSString * urlStr = @"http://img.taopic.com/uploads/allimg/140326/235113-1403260I05466.jpg";
         UIImage * userImag = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
          if (userImag != nil) {//请求成功
               dispatch_async(dispatch_get_main_queue(), ^{//返回主线程
                    self.imageView.image = userImag;
               });
          }else{//请求失败,或请求不到图片
    
          }
    });
    

    相关文章

      网友评论

        本文标题:iOS 网络请求/数据获取/图片上传及加载/多线程加载图片/数据

        本文链接:https://www.haomeiwen.com/subject/yafbbttx.html