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

iOS 網路開發工具:AFNetworking 的 GET、POST、上傳與下載

編輯:iOS 相關資訊

AFNetworking 的常見任務

在 iOS 網路開發中,最常遇到的是網路檢測、GET、POST、檔案上傳、檔案下載與斷點續傳。AFNetworking 把 NSURLSession 與 NSURLConnection 的細節封裝成更直覺的 API,適合快速建立 RESTful 用戶端。

網路監聽

可透過 reachabilityManager 監聽網路狀態。建議在 AppDelegate 啟動時開始監聽,並在需要時停止,避免多餘耗電。

GET 與 POST

GET 適合讀取資料,POST 適合送出表單或 JSON。兩者都可透過 success 與 failure block 處理結果。若需要直接取得原始資料,可把 responseSerializer 改成 AFHTTPResponseSerializer。

manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"API 位址" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

檔案上傳

上傳可使用 constructingBodyWithBlock,把圖片或檔案加入 multipart 表單。圖片可先壓縮,再指定 name、fileName 與 mimeType。

[manager POST:@"API 位址" parameters:parameters constructingBodyWithBlock:^(id formData) {
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"photo"], 1.0);
    [formData appendPartWithFileData:imageData name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

下載與進度

下載時可建立 AFHTTPRequestOperation,並把 outputStream 指向沙盒檔案路徑。透過 setDownloadProgressBlock 可更新 UIProgressView。若要實作斷點續傳,可搭配 pause、resume、cancel 等方法。

NSString *filePath = [NSString stringWithFormat:@"%@/Documents/file", NSHomeDirectory()];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"下載位址"]]];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

iOS 7 的 NSURLSession 寫法

在 iOS 7 之後,也可使用 AFURLSessionManager 建立 uploadTask 或 downloadTask。這種寫法更貼近 NSURLSession,並可搭配 background session 做更完整的背景傳輸。

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