你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS開發——post異步網絡請求封裝

iOS開發——post異步網絡請求封裝

編輯:IOS開發綜合
#import 
#import 
#import Reachability.h

@interface HttpHelper : NSObject

+ (BOOL)NetWorkIsOK;//檢查網絡是否可用
+ (void)post:(NSString *)Url RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block;//post請求封裝

@end

  接下來是實現文件

//  HttpHelper.m
#import HttpHelper.h

@implementation HttpHelper

//這個函數是判斷網絡是否可用的函數(wifi或者蜂窩數據可用,都返回YES)
+ (BOOL)NetWorkIsOK{
    if(
       ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus]
       != NotReachable)
       &&
       ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]
       != NotReachable)
       ){
        return YES;
    }else{
        return NO;
    }
}

//post異步請求封裝函數
+ (void)post:(NSString *)URL RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{
    //把傳進來的URL字符串轉變為URL地址
    NSURL *url = [NSURL URLWithString:URL];
    //請求初始化,可以在這針對緩存,超時做出一些設置
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:20];
    //解析請求參數,用NSDictionary來存參數,通過自定義的函數parseParams把它解析成一個post格式的字符串
    NSString *parseParamsResult = [self parseParams:params];
    NSData *postData = [parseParamsResult dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@POST];
    [request setHTTPBody:postData];
    
    //創建一個新的隊列(開啟新線程)
    NSOperationQueue *queue = [NSOperationQueue new];
    //發送異步請求,請求完以後返回的數據,通過completionHandler參數來調用
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:block];
//    return result;
}

//把NSDictionary解析成post格式的NSString字符串
+ (NSString *)parseParams:(NSDictionary *)params{
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    //實例化一個key枚舉器用來存放dictionary的key
    NSEnumerator *keyEnum = [params keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@%@=%@&,key,[params valueForKey:key]];
        [result appendString:keyValueFormat];
        NSLog(@post()方法參數解析結果:%@,result);
    }
    return result;
}

@end

就是這麼簡單。下面用 登錄的例子 給大家演示一下是怎麼用的。

- (void)login{ 
    NSString *url = @127.0.0.1/login.php;
    NSString *userName = @admin;
    NSString *password =  @root;
    //加入參數
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userName forKey:@phone];
    [params setValue:password forKey:@password];
    //有網絡才發送請求
    if([HttpHelper NetWorkIsOK]){
     //發送請求,並且得到返回的數據
    [HttpHelper post:url RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
      //傳回來的數據存在,則執行改回調甘薯
      if(data){
      //子線程通知主線程更新UI,selector中是要執行的函數,data是傳給這個函數的參數
      //login_callBack就處理返回來的消息,這裡就簡單的輸出,登錄成功
       [self performSelectorOnMainThread:@selector(login_callBack:) withObject:data waitUntilDone:YES];
       }else{
           NSLog(@無效的數據);
       }    
       }];
  }
}

//登錄的回調函數,首先判斷接收的值是不是能登錄。若不能,則提示用戶。若能登錄,則處理segue來跳轉界面
- (void)login_callBack:(id)value{
        NSLog(@登錄成功);
}

 

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