iPhone:使用NSURL请求异步下载数据,而不是[NSData data with CONTENTS ofURL]
嗨,我是个新手,我正试图从googleapi网页下载地理编码数据。我是这样做的:代码:iPhone:使用NSURL请求异步下载数据,而不是[NSData data with CONTENTS ofURL],iphone,ipad,nsurlconnection,asihttprequest,nsoperation,Iphone,Ipad,Nsurlconnection,Asihttprequest,Nsoperation,嗨,我是个新手,我正试图从googleapi网页下载地理编码数据。我是这样做的:代码: NSMutableString *urlStr = [[NSMutableString alloc] initWithString:temp]; NSMutableString *address = [[NSMutableString alloc] initWithString:l.Address]; [address appendString:@" "];
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.
}
根据代码的结构,您可能希望在成功完成(ConnectionDiFinishLoading:)或失败(connection:didFailWithError:)时操作或通知其他对象(委托、通知)