iphone - 从 NSThread 的函数调用时不调用 NSURLConnection 委托(delegate)
<p><p>我发送 <code>NSURLConnection</code> 请求它工作正常。现在我想刷新信息,即从按钮的 IBAction 调用时重新发送 <code>NSURLConnection.Refresh</code> 正在工作。但不适用于 <code>NSThread</code> 方法。我该如何解决这个问题。这里的<code>NSThread</code> 函数用于运行系统时间。当时间等于凌晨 1:00 时,我想刷新 API。但它不是调用 <code>NSURLConnection</code> 的委托(delegate)。</p>
<p>这是 NSURLConnection 代码:</p>
<pre><code>-(void)displays:(model *)place
{
NSString *strs=[@"http://www.earthtools.org/timezone-1.1/" stringByAppendingString:];
NSMutableURLRequest *request=];
NSURLConnection *reqTimeZone=;
; //here request not get start
}
</code></pre>
<p>上面的代码带有一个名为“displays”的函数,参数是一个类的实例,它具有所有位置详细信息。</p>
<p>NSthread函数代码:</p>
<pre><code>- (void) setTimer {
//assign current time
;
}
- (void) countDown {
//count the current time
if(hrs==12&& meridian==@"pm")
;//it calls the displays function but NSURLConnection is not get start.
;
}
</code></pre>
<p>上面的显示函数被称为placedetails分配但<code>NSURLConnection</code>委托(delegate)没有被调用。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>对于要调用的委托(delegate)方法,您需要将线程的运行循环附加到 NSURLConnection。由于您正在创建一个线程并且没有将 NSURLConnection 附加到线程的 RunLoop,因此不会触发连接委托(delegate)方法。</p>
<p>这是一个例子:</p>
<pre><code>- (void)viewDidLoad
{
;
// Do any additional setup after loading the view, typically from a nib.
// I am creating a button and adding it to viewController's view
UIButton *bttn = ;
;
;
;
[ addSubview:bttn];
}
- (void)spawnThreadForDownload
{
;
}
- (void)downloadAndParse
{
@autoreleasepool {
NSURL *url = ;
NSURLRequest *req = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:20.0f];
NSURLConnection *conn = ;
// Run the currentRunLoop of your thread (Every thread comes with its own RunLoop)
[ run];
// Schedule your connection to run on threads runLoop.
forMode:NSDefaultRunLoopMode];
}
}
// NSURLConnectionDelegate methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed with error: %@",);
}
// NSURLConnectionDataDelegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Connection finished downloading");
}
</code></pre></p>
<p style="font-size: 20px;">关于iphone - 从 NSThread 的函数调用时不调用 NSURLConnection 委托(delegate),我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/10537038/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/10537038/
</a>
</p>
页:
[1]