OStack程序员社区-中国程序员成长平台

标题: objective-c - Objective-C "Bad URL"错误 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:58
标题: objective-c - Objective-C "Bad URL"错误

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

欢迎提出任何建议。



Best Answer-推荐答案


你没有初始化你的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/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4