我正在尝试将我的 Obj-C 类之一的一部分转换为能够在 iWatch 上运行,为此,我必须使用 NSURLSession dataTaskWithRequest: 而不是 NSURLConnection sendAsynchronousRequest: 这似乎没有问题(表示 XML 已正确加载和解释)但在我的原始代码中,我为主程序触发了几个 NSNotification 以实现一些可见的修改。
似乎在 NSURLSession completionHandler 内部,它不再起作用了。
这是原始代码:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *answer = [NSDictionary dictionaryWithXMLString:result];
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_START_UPDATING object:nil userInfo:nil];
/* DO SOME STUFF THERE */
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_UPDATING_COMPLETE object:nil userInfo:answer];
}];
现在固定版本如下所示:
NSURLSessionDataTask *subDataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *answer = [NSDictionary dictionaryWithXMLString:result];
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_START_UPDATING object:nil userInfo:nil];
/* DO SOME STUFF THERE */
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_UPDATING_COMPLETE object:nil userInfo:answer];
}];
[subDataTask resume];
疯狂的是,这两个通知都没有使用第二种方法发送/接收,它在第一个版本中运行良好。
同样,我在另一种相同的情况下有一个计时器调用,如下所示:
if (autoRefresh)
refreshTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(refreshInformationTimer:) userInfo:nil repeats:NO];
再一次,它使用 NSURLConnection 工作,但不在 NSURLSessionDataTask 内......
你能帮我解决这个问题吗?
非常感谢。