我的應用程式將 URL 加載到.txt我的 Web 服務器上的檔案。我收到這個警告:
https://(我的文本檔案的路徑)/nowplaying.txt 的同步 URL 加載不應在此應用程式的主執行緒上發生,因為它可能導致 UI 無回應。請切換到異步網路 API,例如 URLSession。
我找不到任何示例來修改我的代碼。這是我現在使用的會產生錯誤的東西。
- (void)viewDidLoad {
[super viewDidLoad];
NSString *stringURL = @"https://(path to my text file)/nowplaying.txt";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *dataString = [NSString stringWithUTF8String:[urlData bytes]];
_lblNowPlaying.text = dataString;
}
uj5u.com熱心網友回復:
你想使用NSURLSession:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *stringURL = @"https://(path to my text file)/nowplaying.txt";
NSURL *url = [NSURL URLWithString:stringURL];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
self.lblNowPlaying.text = string;
});
}
}];
[task resume];
}
請注意,NSURLSession在后臺串行佇列上運行其完成處理程式,因此您必須將標簽的更新分派到主佇列。
添加一些錯誤檢查,檢查NSError物件并檢查 Web 服務器回傳的狀態代碼可能是謹慎的:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *stringURL = @"https://(path to my text file)/nowplaying.txt";
NSURL *url = [NSURL URLWithString:stringURL];
if (!url) {
NSLog(@"%s URL error: %@", __FUNCTION__, stringURL);
return;
}
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%s error: %@", __FUNCTION__, error);
return;
}
if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"%s response: %@", __FUNCTION__, response);
return;
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode < 200 || httpResponse.statusCode >= 300) {
NSLog(@"%s statusCode %ld; response: %@", __FUNCTION__, httpResponse.statusCode, response);
return;
}
if (data) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
self.lblNowPlaying.text = string;
});
}
}];
[task resume];
}
uj5u.com熱心網友回復:
您需要在后臺執行緒中呼叫大計算或長時間等待。完成后,切換到主 (UI) 執行緒以更新 UI,...
在主執行緒(來自主佇列)上運行大計算或同步長時間等待將凍結 UI。
//Start the HUD here
__weak MyObject *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *stringURL = @"https://(path to my text file)/nowplaying.txt";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *dataString = [NSString stringWithUTF8String:[urlData bytes]];
dispatch_async(dispatch_get_main_queue(), ^(void) {
//stop your HUD here
//This is run on the main thread
weakSelf._lblNowPlaying.text = dataString;
});
});
參考:https ://stackoverflow.com/a/27375273/17286292
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/511435.html
標籤:IOS目标-c异步网址
