Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

iOS 網路請求封裝:把 NSURLSession 的 GET 與 POST 收進一個工具類

自 iOS 9.0 起,舊的 NSURLConnection 已被標記為過時,Apple 建議改用 NSURLSession 來完成網路請求。前面已經看過直接用 NSURLSession 發送 GET 與 POST 的做法,這次把它包成一個工具類,之後只要呼叫一個方法就能完成整個流程。

基本思路

  1. 建立一個繼承自 NSObject 的自訂類別,用來呼叫封裝好的 POST 與 GET 方法。
  2. 在自訂類別中提供單例建立方法。
+(instancetype)sharedNewtWorkTool {
    static id _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

參數與回呼的設計

  • urlString:登入介面的字串。
  • paramaters:請求参數字典,key 是伺服器端接收參數的鍵,value 是參數內容。
  • typedef void(^SuccessBlock)(id object, NSURLResponse *response):成功回呼。object 若是 JSON 就直接解析成 OC 的陣列或字典,否則原樣返回 NSData;response 是響應標頭,主要描述伺服器端資訊。
  • typedef void(^failBlock)(NSError *error):失敗回呼,請求失敗時 error 有值。

GET 方法封裝

-(void)GETRequestWithUrl:(NSString *)urlString
               paramaters:(NSMutableDictionary *)paramaters
             successBlock:(SuccessBlock)success
                FailBlock:(failBlock)fail
{
    // 1. 建立請求:先把參數拼到 url 後面
    NSMutableString *strM = [[NSMutableString alloc] init];

    [paramaters enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *paramaterKey = key;     // 伺服器接收參數的 key
        NSString *paramaterValue = obj;   // 參數內容
        [strM appendFormat:@"%@=%@&", paramaterKey, paramaterValue];
    }];

    urlString = [NSString stringWithFormat:@"%@?%@", urlString, strM];
    urlString = [urlString substringToIndex:urlString.length - 1];  // 刪掉最後一個 &
    NSLog(@"urlString:%@", urlString);

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                        timeoutInterval:15];

    // 2. 送出請求,completionHandler 代表請求完成
    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData * _Nullable data,
                                                         NSURLResponse * _Nullable response,
                                                         NSError * _Nullable error) {
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

        if (data && !error) {            // 成功
            id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            if (!obj) {                   // 解析不出來就不是 JSON
                obj = data;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(obj, response);
                }
            });
        } else {                          // 失敗
            if (fail) {
                fail(error);
            }
        }
    }] resume];
}

POST 方法封裝

-(void)POSTRequestWithUrl:(NSString *)urlString
                paramaters:(NSMutableDictionary *)paramaters
              successBlock:(SuccessBlock)success
                 FailBlock:(failBlock)fail
{
    // 1. 建立請求,同樣先拼參數
    NSMutableString *strM = [[NSMutableString alloc] init];
    [paramaters enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *paramaterKey = key;
        NSString *paramaterValue = obj;
        [strM appendFormat:@"%@=%@&", paramaterKey, paramaterValue];
    }];

    NSString *body = [strM substringToIndex:strM.length - 1];
    NSLog(@"%@", body);
    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                     timeoutInterval:15];
    request.HTTPMethod = @"POST";     // 設置請求方法
    request.HTTPBody = bodyData;      // 設置請求體

    // 2. 送出請求
    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData * _Nullable data,
                                                         NSURLResponse * _Nullable response,
                                                         NSError * _Nullable error) {
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        if (data && !error) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            if (!obj) {
                obj = data;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(obj, response);
                }
            });
        } else {
            if (fail) {
                fail(error);
            }
        }
    }] resume];
}

驗收成果

自訂類別大致完成,接著就是驗證的時候。一句話發送 GET 請求:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan");

    NSMutableDictionary *dict = @{@"username": @"zhangsan", @"password": @"zhang"}.mutableCopy;

    [[CZNetworkTool sharedNewtWorkTool]
        GETRequestWithUrl:@"https://127.0.0.1/login/login.php"
               paramaters:dict
             successBlock:^(id object, NSURLResponse *response) {
                 NSLog(@"網絡請求成功:%@", object);
             }
                FailBlock:^(NSError *error) {
                 NSLog(@"網絡請求失敗");
             }];
}

一句話發送 POST 請求:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan");

    NSMutableDictionary *dict = @{@"username": @"zhangsan", @"password": @"zhang"}.mutableCopy;

    [[CZNetworkTool sharedNewtWorkTool]
        POSTRequestWithUrl:@"https://127.0.0.1/login/login.php"
                paramaters:dict
              successBlock:^(id object, NSURLResponse *response) {
                  NSLog(@"網絡請求成功:%@", object);
              }
                 FailBlock:^(NSError *error) {
                  NSLog(@"網絡請求失敗");
              }];
}

執行結果:成功。

Copyright © Linux教程網 All Rights Reserved