iOS SDK 為 HTTP 請求提供了同步與非同步兩套 API,方法上則支援 GET、POST 等。本文先從最直觀的同步 GET 開始,並補上實作時幾乎一定會用到的 URL 編碼工具。
延續 MyNotes「備忘錄」範例應用,這次把資料來源從本地 Notes.xml 改成伺服器端的 Web Service。
#import <UIKit/UIKit.h>
#import "NSString+URLEncoding.h" // URL 編碼與解碼
#import "NSNumber+Message.h" // 把回傳的狀態碼轉成人類可讀的訊息
@interface MasterViewController : UITableViewController
@property (strong, nonatomic) DetailViewController *detailViewController;
// 保存要顯示的資料列表
@property (nonatomic, strong) NSMutableArray *listData;
// 重新載入表視圖
- (void)reloadView:(NSDictionary *)res;
// 開始請求 Web Service
- (void)startRequest;
@end
在 viewDidLoad 的最後呼叫自訂的 startRequest 即可發出請求。
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.detailViewController = (DetailViewController *)
[[self.splitViewController.viewControllers lastObject] topViewController];
[self startRequest];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.listData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSMutableDictionary *dict = self.listData[indexPath.row];
cell.textLabel.text = [dict objectForKey:@"Content"];
cell.detailTextLabel.text = [dict objectForKey:@"CDate"];
return cell;
}
- (void)startRequest {
// ① 組出帶參數的網址
NSString *strURL = [[NSString alloc] initWithFormat:
@"https://iosbook3/mynotes/webservice.php?email=%@&type=%@&action=%@",
@"你的帳號信箱", @"JSON", @"query"];
// ② 先做 URL 編碼再轉成 NSURL
NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
// ③ 建立請求物件
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
// ④ 同步送出並取得回應
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
NSLog(@"請求完成…");
// ⑤ 解析 JSON 並刷新畫面
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
[self reloadView:resDict];
}
務必注意:同步請求會阻塞呼叫它的執行緒。上面這段若直接寫在 viewDidLoad,網路稍慢就會讓畫面凍住。實務上請丟到背景佇列,完成後再回主執行緒更新 UI。
Objective-C 的分類(category)可以替系統類別擴充方法。這裡替 NSString 加上編碼與解碼兩個方法,底層呼叫 Core Foundation 的 C 函式,好處是可以自訂「哪些字元要編碼」。
@interface NSString (URLEncoding)
- (NSString *)URLEncodedString;
- (NSString *)URLDecodedString;
@end
@implementation NSString (URLEncoding)
- (NSString *)URLEncodedString {
NSString *result = (NSString *)CFBridgingRelease(
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, // ①
(CFStringRef)self,
NULL, // ② 不需編碼的合法字元
CFSTR("+$,#[] "), // ③ 需強制編碼的字元
kCFStringEncodingUTF8));
return result;
}
- (NSString *)URLDecodedString {
NSString *result = (NSString *)CFBridgingRelease(
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
kCFAllocatorDefault,
(CFStringRef)self,
CFSTR(""), // ④ 不解碼的字元集
kCFStringEncodingUTF8));
return result;
}
@end
CFURLCreateStringByAddingPercentEscapes 是 Core Foundation 提供的 C 函式,負責把內容轉成 URL 編碼。第三個參數指定「本身已是合法 URL 字元、不需編碼」的集合,例如 !*();第四個參數則指定「本身合法但要強制編碼」的集合,例如 +$,#[] 與空白。
CFURLCreateStringByReplacingPercentEscapesUsingEncoding 作用正好相反,負責把百分號編碼還原。
Foundation 也提供了對應的 Objective-C 方法:stringByAddingPercentEscapesUsingEncoding: 與 stringByReplacingPercentEscapesUsingEncoding:。差別在於它們無法自訂要編碼的字符集,彈性不如上面的 C 函式。若你的參數只含一般中英數字,用它們就夠了。