我正在使用stringWithcontentsofurl从我的web服务器下载一些字符串到应用程序,但我想更新UI以显示某种类型的加载器。我正在下载一些字符串(有时可能多达100个),所以用户可以显示一些东西,这样他们就知道应用程序不会崩溃,因为现在UI卡住了,我不能显示UILoader或类似的东西。有这样做的选择吗?或者,在可能的情况下,可以替代stringWithcontentsofurl?
你好,埃里克
发布于 2011-08-10 08:13:26
这是“延迟加载”的典型案例。请参阅Apple的示例代码:
http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html
在阅读代码时,用“string”替换"images“应该很容易。
您希望在标签中显示一个占位符,如"(fetching information)“或类似的,然后在后台加载信息,要么自己线程化fetch (异步fetching),要么使用像ASIHTTPRequest这样的库为您处理所有异步螺母和螺栓,并在fetch完成后调用委托方法。
发布于 2013-05-15 15:01:16
尝尝这个。它在后台加载数据。如果稍后更新UI (在异步加载中),请确保在主线程上执行此操作。
-(void)loadappdetails:(NSString*)appid {
NSString* searchurl = [@"https://itunes.apple.com/lookup?id=" stringByAppendingString:appid];
[self performSelectorInBackground:@selector(asyncload:) withObject:searchurl];
}
-(void)asyncload:(NSString*)searchurl {
NSURL* url = [NSURL URLWithString:searchurl];
NSError* error = nil;
NSString* str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(@"Error: %@", error);
}
NSLog(@"str: %@", str);
}发布于 2011-08-10 08:10:11
不幸的是,stringWithContentsOfURL是一个同步方法,这意味着它将阻塞您的线程,并且在它运行时您不会收到任何回调。这也不利于用户体验。
另一种方法是使用NSURLConnection手动设置您自己的请求,并点击连接的委托方法以显示某种进度条。具体地说,您需要使用connection:didReceiveData:和connectionDidFinishLoading:
收到所有数据后,使用以下命令获取字符串。
NSString *theString = [[NSString alloc] initWithData:yourData encoding:UTF8StringEncoding];https://stackoverflow.com/questions/7004494
复制相似问题