37

当我尝试从后台线程向服务器发出异步请求时,我遇到了问题。我从来没有得到这些请求的结果。显示问题的简单示例:

@protocol AsyncImgRequestDelegate
-(void) imageDownloadDidFinish:(UIImage*) img;
@end


@interface AsyncImgRequest : NSObject
{
 NSMutableData* receivedData;
 id<AsyncImgRequestDelegate> delegate;
}

@property (nonatomic,retain) id<AsyncImgRequestDelegate> delegate;

-(void) downloadImage:(NSString*) url ;

@end



@implementation AsyncImgRequest
-(void) downloadImage:(NSString*) url 
{  
 NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
             cachePolicy:NSURLRequestUseProtocolCachePolicy
            timeoutInterval:20.0];
 NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
 if (theConnection) {
  receivedData=[[NSMutableData data] retain];
 } else {
 }  

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  [delegate imageDownloadDidFinish:[UIImage imageWithData:receivedData]];
  [connection release];
  [receivedData release];
}
@end

然后我从主线程调用它

asyncImgRequest = [[AsyncImgRequest alloc] init];
asyncImgRequest.delegate = self; 
[self performSelectorInBackground:@selector(downloadImage) withObject:nil];

方法downloadImage如下:

-(void) downloadImage
{
 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 [asyncImgRequest downloadImage:@"http://photography.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/Photography/Images/POD/l/leopard-namibia-sw.jpg"];
 [pool release];
}

问题是永远不会调用 imageDownloadDidFinish 方法。而且没有任何方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response

被称为。但是,如果我更换

 [self performSelectorInBackground:@selector(downloadImage) withObject:nil]; 

经过

 [self performSelector:@selector(downloadImage) withObject:nil]; 

一切正常。我假设后台线程在异步请求完成之前就死了,这会导致问题,但我不确定。我对这个假设是否正确?有没有办法避免这个问题?

我知道我可以使用同步请求来避免这个问题,但这只是一个简单的例子,实际情况更复杂。

提前致谢。

4

3 回答 3

59

Yes, the thread is exiting. You can see this by adding:

-(void)threadDone:(NSNotification*)arg
{
    NSLog(@"Thread exiting");
}

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(threadDone:)
                                             name:NSThreadWillExitNotification
                                           object:nil];

You can keep the thread from exiting with:

-(void) downloadImage
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    [self downloadImage:urlString];

    CFRunLoopRun(); // Avoid thread exiting
    [pool release];
}

However, this means the thread will never exit. So you need to stop it when you're done.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    CFRunLoopStop(CFRunLoopGetCurrent());
}

Learn more about Run Loops in the Threading Guide and RunLoop Reference.

于 2009-11-13T15:46:36.790 回答
1

您可以在后台线程上启动连接,但您必须确保在主线程上调用委托方法。这不能用

[[NSURLConnection alloc] initWithRequest:urlRequest 
                                delegate:self];

因为它立即开始。

这样做来配置委托队列,它甚至可以在辅助线程上工作:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest 
                                                              delegate:self 
                                                      startImmediately:NO];
[connection setDelegateQueue:[NSOperationQueue mainQueue]];
[connection start];
于 2014-04-14T18:54:32.490 回答
0

NSURLRequests 无论如何都是完全异步的。如果您需要从主线程以外的线程创建 NSURLRequest,我认为最好的方法就是NSURLRequest 主线程中创建。

// Code running on _not the main thread_:
[self performSelectorOnMainThread:@selector( SomeSelectorThatMakesNSURLRequest ) 
      withObject:nil
      waitUntilDone:FALSE] ; // DON'T block this thread until the selector completes.

所有这一切都是从主线程发出 HTTP 请求(这样它就可以正常工作并且不会神秘地消失)。HTTP 响应将像往常一样返回到回调中。

如果你想用 GCD 做这个,你可以去

// From NOT the main thread:
dispatch_async( dispatch_get_main_queue(), ^{ //
  // Perform your HTTP request (this runs on the main thread)
} ) ;

MAIN_QUEUE主线程上运行。

所以我的 HTTP get 函数的第一行如下所示:

void Server::get( string queryString, function<void (char*resp, int len) > onSuccess, 
                  function<void (char*resp, int len) > onFail )
{
    if( ![NSThread isMainThread] )
    {
        warning( "You are issuing an HTTP request on NOT the main thread. "
                 "This is a problem because if your thread exits too early, "
                 "I will be terminated and my delegates won't run" ) ;

        // From NOT the main thread:
        dispatch_async( dispatch_get_main_queue(), ^{
          // Perform your HTTP request (this runs on the main thread)
          get( queryString, onSuccess, onFail ) ; // re-issue the same HTTP request, 
          // but on the main thread.
        } ) ;

        return ;
    }
    // proceed with HTTP request normally
}
于 2013-05-07T20:30:37.127 回答