使用 NSURL URLWithString: 構建帶查詢參數的 URL 時,編譯錯誤 Too many arguments expects 1 have 2。
NSString *myString = @"1994";
NSURL *url = [NSURL URLWithString:@"https://example.com/api.php/?data=%@", myString];
// 錯誤:URLWithString: 只接受 1 個參數,無法直接格式化
NSString *myString = @"1994";
// 先用 stringWithFormat 組合完整字串,再建立 NSURL
NSString *urlString = [NSString stringWithFormat:@"https://example.com/api.php/?data=%@", myString];
NSURL *url = [NSURL URLWithString:urlString];
// 或使用 NSURLComponents (iOS 7+ 推薦)
NSURLComponents *components = [NSURLComponents componentsWithString:@"https://example.com/api.php/"];
components.queryItems = @[[NSURLQueryItem queryItemWithName:@"data" value:myString]];
NSURL *url = components.URL; // 自動處理編碼
NSString *myString = @"1994";
NSString *postBody = [NSString stringWithFormat:@"data=%@", myString];
NSURL *url = [NSURL URLWithString:@"https://example.com/api.php/"]; // 基礎 URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSData *postData = [postBody dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postData.length]
forHTTPHeaderField:@"Content-Length"];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (!error && response.statusCode >= 200 && response.statusCode < 300) {
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"回應: %@", result);
} else {
NSLog(@"錯誤: %@, 狀態碼: %ld", error, (long)response.statusCode);
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
// 更新 UI
NSLog(@"非同步回應: %@", result);
});
}
} else {
NSLog(@"網路錯誤: %@", error);
}
}];
[task resume];
NSURL;推薦 NSURLComponents 自動處理編碼setHTTPBody: 需 NSData,編碼用 NSUTF8StringEncodingContent-Type 為 application/x-www-form-urlencodedNSURLSession 非同步