2011-06-30 19 views
0

我可以通过NSURLConnection从代码库中的任何其他部分异步成功检索数据,除了函数在我的子类TileOverlayView类中。异步调用不工作在多线程代码部分(MKOverlay canDraw)

我正在修改名为tileMap的MapKit示例,以从服务器下载切片并在地图上覆盖该信息。在canDrawMapRect中,我调用了overlay类中的一个函数,该函数依次创建url并打开一个连接。我已经测试了我的连接类并确认它确实有效。我已经在覆盖的初始化函数中运行了它,并且成功地运行了overlayView。由于我可以将它们放入浏览器中,并且它们显示正确的png,因此这些网址也很好。我知道canDrawMapRect正在多线程上运行,我只有线程的新手体验。

这里是我的连接代码,

- (id)initWithStringUrl: (NSString*) url { 

    NSLog(@"Test Connect Init URL %@", url); 

    self = [super init]; 
    if (self) 
    { 
     [self loadURL:[NSURL URLWithString:url]];  
    } 

    return self; 
} 
+ (UIImage*)connectSynchronousWithURL:(NSString*) url { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 

    NSURLResponse* response = [[NSURLResponse alloc] init]; 
    NSError* error = [[NSError alloc] init]; 
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    UIImage *image = [UIImage imageWithData: data]; 

    return image; 
} 
- (BOOL)loadURL:(NSURL *)inURL { 
    NSURLRequest *request = [NSURLRequest requestWithURL:inURL]; 
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self]; 

    if (conn) { 
     receivedData = [[NSMutableData data] retain]; 
     NSLog(@"Connection Success"); 
    } else { 
     NSLog(@"Connection Failed");   
     return FALSE; 
    } 

    return TRUE; 
} 
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"didReceiveResponse"); 
    [receivedData setLength:0]; 
} 
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data { 
    NSLog(@"didReceiveData"); 
    [receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)conn { 
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]); 
} 

漂亮的标准的东西。如果我在TileOverlayView的init中运行代码,它将工作得很好,但如果我在canDrawMapRect中运行它,则不会调用任何委托函数。我想还值得一提的是,与canDrawMapRect方法中的服务器的同步连接确实有效。我不明白T_T

任何帮助将不胜感激。谢谢。

回答

0

从关于NSURLConnection的文档,这几乎总结了它。

请注意,这些委托方法将在启动相关NSURLConnection对象的异步加载操作的线程上调用。

看起来像我将需要使用CFRunLoopRun()CFRunLoopStop(CFRunLoopGetCurrent());保持线程活着。或者找到在线程中进行这些异步调用的替代方法。

+0

[链接](http://stackoverflow.com/questions/5427168/asynchronous-nsurlconnection-whats-going-on-underneath)引用此链接。 – Biclops