如果您使用 NSURLConnection 它会自动在另一个线程上运行。
在你的 viewDidLoad 中:
NSURLRequest *req = [NSURLRequest requestWithURL:theURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
那么你需要一些自定义方法。如果您输入-connection
并按 Esc,您将看到您可以使用的所有不同方法。你需要三个:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// this is called when there is a response
// if you're collecting data init your NSMutableData here
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// each time the connection downloads a
// packet of data it gets send here
// so you can do [myData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
// the connection has finished so you can
// do what you want with the data here
}
这基本上就是它的全部内容。NSURLConnection 自己处理所有的多线程,你不必担心。现在您可以创建一个活动指示器并显示它,它会工作,因为主线程是空的。:)