目标C“错误的URL”错误

时间:2012-12-17 12:50:39

标签: objective-c ios nsurlconnection

我正在尝试从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];

任何建议都是最受欢迎的。

1 个答案:

答案 0 :(得分:4)

您未初始化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];