异步调用不能在多线程代码段中工作(MKOverlay canDraw)

时间:2011-06-30 19:42:06

标签: ios asynchronous mapkit nsurlconnection

我可以通过NSURLConnection从代码库中的任何其他部分异步检索数据,除了我的子类canDrawMapRect类中的TileOverlayView函数。

我正在修改名为tileMap的MapKit示例,以便从服务器下载切片并将该信息覆盖在地图上。在canDrawMapRect中,我在overlay类中调用一个函数,该函数又创建了url并打开了一个连接。我已经测试了我的连接类,并确认它确实有效。我已经在overlay和overlayView的init函数中成功运行了它。网址也很好,因为我可以将它们放在浏览器中,并显示正确的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

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

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

  

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

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