我用大中央調度(GCD)方法來實現這一點。這裏有一個例子適合我在一個簡單的測試應用程序(我不知道它是否適用於靜態庫,但可能值得一看)。我正在使用ARC。
在這個例子中,我從我的viewDidLoad方法開始了一些後臺工作,但是你可以從任何地方啓動它。關鍵是「dispatch_async(dispatch_get_global_queue ...」在後臺線程中運行該塊。看到這個答案對於這種方法的一個很好的解釋:https://stackoverflow.com/a/12693409/215821
這裏是我的viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL),
^(void) {
[self doStuffInBackground];
});
}
的doStuffInBackground方法在此時後臺運行,所以你可以只使用NSURLConnection的同步。在我這裏的例子中,該方法循環進行網絡調用,直到可能的其他代碼集backgroundStuffShouldRun = false。網絡通話時間爲10秒。通話結束後,我正在更新UI標籤以顯示進度。請注意,UI更新是使用「dispatch_async(dispatch_get_main_queue()...」)執行的。這將根據需要在UI線程上運行UI更新。
此背景工作存在一個潛在問題:無法取消http請求本身。不過,與10秒的短暫停,你會等待10秒的最大的線程局外人(可能有些事件在UI)後中止本身設置backgroundStuffShouldRun =假。
- (void)doStuffInBackground
{
while (backgroundStuffShouldRun) {
// prepare for network call...
NSURL* url = [[NSURL alloc] initWithString:@"http://maps.google.com/maps/geo"];
// set a 10 second timeout on the request
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10];
NSError* error = nil;
NSURLResponse *response = nil;
// make the request
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// were we asked to stop the background processing?
if (!backgroundStuffShouldRun) {
return;
}
// process response...
NSString* status = @"Success";
if (error) {
if (error.code == NSURLErrorTimedOut) {
// handle timeout...
status = @"Timed out";
}
else {
// handle other errors...
status = @"Other error";
}
}
else {
// success, handle the response body
NSString *dataAsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataAsString);
}
// update the UI with our status
dispatch_async(dispatch_get_main_queue(), ^{
[statusLabel setText:[NSString stringWithFormat:@"completed network call %d, status = %@", callCount, status]];
});
callCount++;
sleep(1); // 1 second breather. not necessary, but good idea for testing
}
}