在 iOS 早期網路編程中,NSURLConnection 是常見的請求方式。它可以同步取得資料,也可以透過 queue 與 completionHandler 非同步接收回傳結果。
同步方式會在目前執行緒等待回應。它不會新建執行緒,因此在資料回傳前,目前流程會被卡住,容易造成介面無回應。
[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
非同步方式會使用 queue 接收回傳資料,適合網路請求。完成後,會執行 completionHandler 中的程式。
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"data length: %ld", (unsigned long)data.length);
}];在 App 中,網路請求通常應避免阻塞主線程。若需要登入、表單驗證或資料抓取,建議使用非同步方式,並在回調中處理錯誤與畫面更新。
此外,帳號、密碼等敏感資料不應直接以純文字接在 URL 上。正式環境應使用 HTTPS,並避免把敏感資訊寫入日誌。