iOS 原生网络请求写法

来源:互联网 发布:爱养成2圣灵之使数据 编辑:程序博客网 时间:2024/06/11 16:20
//网络请求
   
NSURLSession * mySession = [NSURLSessionsharedSession];
   
NSURL * fullURL = [NSURLURLWithString:[NSStringstringWithFormat:@"%@/%@",host,shoplisturl]];
   
NSMutableURLRequest * request = [NSMutableURLRequestrequestWithURL:fullURLcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:7.0];
    request.
HTTPMethod= @"POST";
    [request
addValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
   
NSString * paramStr = [NSStringstringWithFormat:@"cate_id=%@&business=%@&p=%@&sort=%@&num=%@&recommend=%@&keyword=%@&lng_lat=%@&uid=%@&token=%@",cateID,businessID,page,sort,num,recommend,keyword,lng_lat,userID,token];
    request.
HTTPBody= [paramStr dataUsingEncoding:NSUTF8StringEncoding];
   
NSURLSessionDataTask * task = [mySessiondataTaskWithRequest:requestcompletionHandler:^(NSData* _Nullable data,NSURLResponse* _Nullable response,NSError* _Nullable error) {
       
//判断接口是否成功返回
       
if (error) {
           
//接口访问失败
           
NSLog(@"error:%@",error.localizedDescription);
           
NSLog(@"%s",__func__);
           
           
NSInteger status =0;
           
           
if (callback) {
                callback(status,
@"网络不给力");
            }
        }
else
        {
           
//接口访问成功
           
//JSON解析
           
NSError * parseError1 =nil;
           
NSDictionary * dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:&parseError1];
           
if (parseError1) {
               
NSLog(@"JSON解析错误");
               
return;
            }
           
NSLog(@"data:%@", dic);
           
           
NSArray *dataArray = [dicobjectForKey:@"info"];
           
NSInteger status = [[dicobjectForKey:@"status"]integerValue];
           
if (status == 1) {
               
if (callback) {
                   
dispatch_async(dispatch_get_main_queue(), ^{
                        callback(status,dataArray);
                    });
                }
            }
else{
//                [self showHUDInWindowJustWithText:[dic objectForKey:@"info"] disMissAfterDelay:1.0];
               
               
if (callback) {
                   
dispatch_async(dispatch_get_main_queue(), ^{
                        callback(status,
nil);
                    });
                }
            }
        }
       
    }];
    [task resume];
0 0