我可以通过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
任何帮助将不胜感激。谢谢。
[链接](http://stackoverflow.com/questions/5427168/asynchronous-nsurlconnection-whats-going-on-underneath)引用此链接。 – Biclops