1
嗨,我是新手,我試圖從googleapi網頁下載地理編碼數據。我做到了使用此:代碼:iPhone:與NSURL請求異步下載數據,而不是[NSData datawithContents ofURL]
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];
它工作得很好,但故障是,它鎖定了我的圖形用戶界面,因爲它全部完成同步。
有人建議我使用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.
}