所以我有一个连接到内部 IP 地址的应用程序。所以我想实现代码以确保创建 NSSURLConnections(即连接到无线网络),因为如果我不在无线网络上,我将无法连接到服务器。问题是在我可以检查它之前卡住了。我实现了
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
但它永远不会被调用。关于如何进行的任何想法?
这是我创建连接的代码
NSURL *url = [NSURL URLWithString:@"http://192.168.192.4/file.php"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
在这最后一行之后,它在远处的狂野蓝色中熄灭了!
**更新***
这是按下按钮时调用的方法。
NSURL *url = [NSURL URLWithString:@"http://192.168.192.4/file.php"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
[connection release];
我还实现了这些方法:
didFailWithError:(NSError *)
完成加载
didRecieveData
我只是将连接更改为 (nonatomic, retain) ...strong 没有自动完成选项。有什么指点吗?
最佳答案
在这种情况下,您没有使用 ARC,但您遇到了类似的问题。您在分配/初始化之后立即释放 connection
,因此连接永远不会启动。删除 [connection release]
并通过两个委托(delegate)方法中的属性释放它以完成连接,如下所示。
供引用:
如果您的项目正在使用 ARC,connection
将在运行循环结束后立即释放,因为没有任何东西保留它。尝试创建一个(非原子的,强的)属性来保留连接。连接完成后将属性清零。
在MyClass.h中
@property (nonatomic, strong) NSURLConnection * connection;
在 MyClass.m 中
@implementation MyClass
@synthesize connection;
- (void)requestData
{
// create request
self.connection = [NSURLConnection connectionWithRequest:...];
// in connection delegate method for successful completion or error set self.connection = nil;
}
编辑:阐明了 ARC 信息
编辑 #2:在顶部添加非弧形答案
关于ios - 无法获取 NSURLConnection,但应用一直在等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033920/