你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS中的網絡請求

IOS中的網絡請求

編輯:IOS開發綜合
使用NSURLConnection的網絡請求,最好定義一個類方法,在主線程中直接調用類方法獲取請求到的網絡數據

//構建類方法--請求網絡
+ (void)requestData:(NSString *)urlStr
         httpMethod:(NSString *)method
             params:(NSMutableDictionary *)params
    comletionHandle:(void (^)(id result))block
{
    //1.構建URL
    urlStr = [BASE_URL stringByAppendingString:urlStr];
    NSURL *url = [NSURL URLWithString:urlStr];
    //2.request構建
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 60;
    request.HTTPMethod = method;
    //判斷請求方式
    if ([method isEqualToString:@"GET"]) {
        //往URL後直接拼接
        NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@"?"];
        //拼接樣式
        //拼接URL---》https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00SllYeF568jxC1082c39bc40_Vqyg&username=aaa&pass=bbb

        //循環拼接參數字典
        for (int i = 0; i < params.count; i ++) {
            NSString *key = params.allKeys[i];
            NSString *value = params[key];
            
            //開始拼接=
            [paramsStr appendFormat:@"%@=%@",key,value];
            //拼接&符號
            //最後一個不再用&符號拼接
            if (i < params.count-1) {
                [paramsStr appendFormat:@"&"];
            }
            
        }
        //得到拼接後的URL(將主URL與拼接的URL 拼接在一起得到完整的URL)
        request.URL = [NSURL URLWithString:[urlStr stringByAppendingString:paramsStr]];
        
    }else if ([method isEqualToString:@"POST"]){
        //將參數添加到請求體中

        NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@""];
        for (int i = 0; i < params.count; i ++) {
            NSString *key = params.allKeys[i];
            NSString *value = params[key];
            
            //開始拼接
            [paramsStr appendFormat:@"%@=%@",key,value];
            if (i < params.count - 1) {
                [paramsStr appendFormat:@"&"];
            }
        }
        //添加到請求體中
        //將字符串轉化為數據
        NSData *data = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPBody = data;
    }
    
    //3.開始請求網絡
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
         if (connectionError) {
             NSLog(@"error----%@",connectionError);
             return ;
         }
         //成功獲取數據
         //開始解析數據
         id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         //返回數據
         dispatch_async(dispatch_get_main_queue(), ^{
             block(result);
         });
         
     }];
}

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved