在 iOS 開發中,原生網路請求是許多 App 的基礎能力。本文以 GET 請求為例,整理從建立 URL、設定請求標頭、發送請求到解析 JSON 並更新畫面的完整流程,適合需要快速回顧或複製使用的開發者。
NSURL 與 NSMutableURLRequest。setValue:forHTTPHeaderField: 設定請求標頭,例如 API 所需的驗證欄位。NSURLSession 建立工作,並呼叫 resume 啟動請求。-(void)getResult {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
NSString *path = @"https://a.apix.cn/apixlife/phone/phone";
NSString *pathWithPhone = [NSString stringWithFormat:@"%@?phone=%@", path, _phoneNumFD.text];
NSString *urlPath = [pathWithPhone stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
NSURL *url = [NSURL URLWithString:urlPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";
[request setValue:@"你的 apix-key" forHTTPHeaderField:@"apix-key"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[hud hide:YES];
});
if (error) {
NSLog(@"請求失敗:%@", error);
return;
}
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if ([result[@"message"] isEqualToString:@"success"]) {
NSDictionary *dataDic = result[@"data"];
NSString *city = dataDic[@"city"];
NSString *province = dataDic[@"province"];
NSString *belong = [NSString stringWithFormat:@"%@ · %@", province, city];
dispatch_async(dispatch_get_main_queue(), ^{
_resultLB.text = belong;
});
}
}];
[task resume];
}
請求標頭常用於 API 驗證或版本識別,例如 apix-key。若服務端要求中文參數,務必先做 URL 編碼,否則可能出現請求失敗或參數被截斷的問題。回呼區塊可能位於背景執行緒,因此更新 UI 時應切回主執行緒。