您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 網路請求:使用 ASIHTTPRequest 實作簡易請求

編輯:iOS 相關資訊

簡介

ASIHTTPRequest 是一套廣為使用的第三方網路庫,能大幅精簡程式碼、提升開發效率。本文示範如何整合它並完成一個非同步的 POST 請求。

準備工作

一、匯入第三方庫 ASIHTTPRequest。

二、整合後往往會出現大量編譯錯誤,原因通常有兩個:一是缺少 Xcode 自帶的幾個系統framework;二是該庫並未使用 ARC(自動引用計數)。

三、解決方案:

  1. 匯入四個系統文件:MobileCoreServices.framework、SystemConfiguration.framework、CFNetwork.framework 與 libz.1.2.5.dylib。
  2. 手動關閉 ARC:在工程 Build Phases 的 Compile Sources 中,找到 ASIHTTP 相關的檔案,點擊右側並加上 -fno-objc-arc 旗標。
  3. 完成上述設定後重新編譯,即可正常運行。

實作非同步請求

#import "ASIHTTPRequest.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestHttp];
}

- (void)requestHttp {
    // 建立 URL 物件
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
        @"https://api.kuaidi100.com/api?id=d6b9888b0da96f6b&com=%@&nu=%@&show=0&muti=1&order=desc&display=mobile"]];
    NSLog(@"url======%@", url);

    // 建立請求物件
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    // 送出請求,並在完成區塊中處理返回的 JSON 資料
    [request setCompletionBlock:^{
        NSError *error = nil;
        // 以字典接收返回的 JSON 資料
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData
                                                                   options:kNilOptions
                                                                     error:&error];
        NSLog(@"%@", dictionary);

        // 取出 data 欄位並放入陣列
        NSArray *arr = [dictionary objectForKey:@"data"];

        // 遍歷並整理每一筆資料
        for (NSDictionary *temp in arr) {
            [self.array addObject:[NSString stringWithFormat:@"%@ /n%@",
                                   [temp objectForKey:@"time"], [temp objectForKey:@"context"]]];
        }

        // 將整理後的資料組合成字串
        for (NSString *temp in self.array) {
            [self.mutableString appendString:[NSString stringWithFormat:@"%@/n", temp]];
            NSLog(@"temp==== %@", temp);
        }

        // 將結果字串賦值給 Label 顯示
        self.jieGuoLale.text = self.mutableString;
        NSLog(@"self.jieGuoLale.text======%@", self.jieGuoLale.text);
    }];

    // 若請求失敗,彈出警示框
    [request setFailedBlock:^{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"問題警告:網路連結異常,請稍後再試"
                                                           delegate:nil
                                                  cancelButtonTitle:@"退出"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

    // 送出一個非同步請求
    [request startAsynchronous];
}

透過 setCompletionBlock: 與 setFailedBlock: 分別處理成功與失敗的情境,再呼叫 startAsynchronous 即可在背景執行請求,避免阻塞主執行緒。相較於原生 API,ASIHTTPRequest 讓整個流程更加直覺簡潔。

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