0

因此,我正在尝试连接到远程服务器以获取和显示数据。在viewDidLoad我使用 anNSThread来调用一个名为doSomething

- (void)doSomething
{        
    @autoreleasepool
    {                
        NSMutableURLRequest *httpRequest = [NSMutableURLRequest requestWithURL:someURL];
        [httpRequest setHTTPMethod:@"POST"];
        [httpRequest setValue:[NSString stringWithFormat:@"%d", httpRequestParametersClean.length] forHTTPHeaderField:@"Content-Length"];
        [httpRequest setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [httpRequest setHTTPBody:httpRequestParametersClean];

        (void)[[NSURLConnection alloc] initWithRequest:httpRequest delegate:self];

        for (NSString* key in response)
        {
             // loop through returned values
        }
     }
}

中的代码viewDidLoad

 [NSThread detachNewThreadSelector:@selector(someURL) toTarget:self withObject:nil];

然后我有一个REFRESH按钮,当点击它时doSomething,只需简单地说[self doSomething]

我的问题是,加载视图时,服务器的响应为空。在单击刷新按钮之前,我仍然没有得到任何响应。奇怪的!我究竟做错了什么?

4

1 回答 1

3

A NSURLConnectioncreated with异步initWithRequest:delegate:工作,调用委托函数, , ... 稍后,当从服务器读取数据时。您的代码甚至没有连接,因此无论如何都不会发生任何事情。connection:didReceiveResponse:connection:didReceiveData:start

解决问题的最简单方法是使用同步版本

sendSynchronousRequest:returningResponse:error:

NSURLConnection。如果doSomething在单独的线程中执行,则不会阻塞 UI。

补充:(感谢@geowar 提到这一点。)请注意,您也可以使用基于委托的NSURLConnection方法。这些更灵活(参见例如https://stackoverflow.com/a/15591636/1187415进行比较)。另一个不错的选择是sendAsynchronousRequest:queue:completionHandler:,它会自动创建一个后台线程。

于 2013-03-31T18:07:11.593 回答