我正在尝试从我的 Objective C 代码中设置对某个 URL 的 Http GET 请求。无论我做什么,或者使用哪个 URL,我都会收到以下错误:
Connection Failed: Error Domain=NSURLErrorDomain
Code=-1000 "bad URL" UserInfo=0x755c440
{NSUnderlyingError=0x7561950 "bad URL", NSLocalizedDescription=bad URL}
我是 iOS 开发新手,所以我不确定我这样做是否正确。我遵循了苹果文档并在各种论坛中寻找答案,即使这样我也收到了这个错误。
这是我的代码:
NSString *url = [NSString stringWithFormat: @"http://example.com/api/%@/%@", str1, str2];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(@"URL - %@", encodedUrl); // Checking the url
NSMutableURLRequest *theRequest= [[NSMutableURLRequest alloc] init];
[theRequest setHTTPMethod:@"GET"];
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
非常欢迎任何建议。
最佳答案
您没有初始化您的theRequest
。
如果您不将其返回值分配给变量,则该行不会执行任何操作。
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
这是您应该使用的代码:
NSString *url = [NSString stringWithFormat: @"http://example.com/api/%@/%@", str1, str2];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(@"URL - %@", encodedUrl); // Checking the url
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
关于objective-c - Objective-C "Bad URL"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914530/