嗨,我
是一个新手,我正在尝试从谷歌api网页下载地理编码数据。我用这个做了:代码:
NSMutableString *urlStr = [[NSMutableString alloc] initWithString:temp];
NSMutableString *address = [[NSMutableString alloc] initWithString:l.Address];
[address appendString:@" "];
[address appendString:l.CityName];
[address appendString:@" "];
[address appendString:l.State];
[address appendString:@" "];
[address appendString:l.PostalCode];
NSArray *addressArray = [address componentsSeparatedByString:@" "];
[address release];
NSString *a = [addressArray componentsJoinedByString:@"+"];
[urlStr appendString:a];
[urlStr appendString:@"&sensor=false"];
NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [NSData dataWithContentsOfURL:url];
它工作正常,但故障是它锁定了我的 GUI,因为它都是同步完成的。
有人建议我使用 NSURLrequest 异步执行此操作。所以我去了苹果网站。从那里我看到了他们的榜样。然而,我仍然卡住了。如何将上述同步请求代码转换为异步请求?到目前为止,这就是我所拥有的,但我不确定这是否有效......有点困惑...有人可以用这段代码指出我的方向吗?
NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//create NSURL request for asynchronous processing
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection= [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
receivedData = [[NSMutableData data] retain];
}
else
{
// Inform the user that the connection failed.
}
Using NSURLConnection
根据您构建代码的方式,您需要在成功完成时执行或通知其他对象(委托、通知)(连接DidFinishLoad:)或失败(连接:didFailWithError:)。