在NSURLSession dataTaskWithRequest中未触发NSNotification:

时间:2016-08-15 15:17:14

标签: objective-c nsurlsession nsnotificationcenter nsnotification nsurlsessiondatatask

我正在尝试将我的一个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内...

你能帮我解决这个问题吗?

非常感谢。

0 个答案:

没有答案