网络请求判断连接和状态码

来源:互联网 发布:网络错误678是什么意思 编辑:程序博客网 时间:2024/05/01 20:13

    NSURL *url = [NSURLURLWithString:@"http://news.coolban.com";

   [NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response,NSData *_Nullable data,NSError *_Nullable connectionError) {

        

        //连接错误

        if(connectionError){

            errorBlock();

//            NSLog(@"%@",connectionError);

            return;

        }

        

        //得到状态码

        //判断状态码是200或者304就是成功

        NSHTTPURLResponse *httpResponse =  (NSHTTPURLResponse *)response;

        if(httpResponse.statusCode ==200 || httpResponse.statusCode ==304){

            //访问成功

            //json反序列化

            id result =  [NSJSONSerializationJSONObjectWithData:data options:0 error:NULL];

            

            NSMutableArray *mArray = [NSMutableArrayarray];

            //遍历array

            [result enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL * _Nonnull stop) {

                CZNews *news = [CZNewsnewsWithDictionary:obj];

                [mArray addObject:news];

            }];

            

            sucessBlock(mArray.copy);

            

        }else{

            errorBlock();

//            NSLog(@"服务器错误");

        }

        

    }];


0 0
原创粉丝点击