【问题标题】:NSURLConnection delegate methods are called in Simulator but not in DeviceNSURLConnection 委托方法在模拟器中调用,但在设备中不调用
【发布时间】:2013-06-01 10:19:13
【问题描述】:

我创建了一个NSObject,它从 php Web 服务下载一些数据。问题是当我在模拟器中运行应用程序时运行良好,但在设备中没有调用委托方法。我不知道为什么。我编写了所有的委托方法,但没有一个被调用。这是NSObject 代码的一部分:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:hostStr]];
 NSLog(@"%@ URL Engine",hostStr);
 dispatch_async(dispatch_get_main_queue(), ^{
 _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];

       // while(!finished) {
         //   [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
        //}
        [_connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        [_connection start];
    });

【问题讨论】:

  • _connection 是一个强大的 iVar 吗?
  • 仅使用xcode 标签来回答有关 IDE 本身的问题。谢谢!
  • 为什么要使用主队列运行这段代码?如果我理解正确,您想将数据加载到后台队列中,因此您应该将 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 作为 dispatch_async 的第一个参数传递。加载数据后,在您的委托中输入如下内容: dispatch_async(dispatch_get_main_queue(), ^(void){ //Run UI Updates });

标签: iphone ios development-environment


【解决方案1】:

调用 dispatch_async 让连接在主线程队列上运行很棘手。

如果你想让你的代理在主线程上被调用,试试这个:

 [self performSelectorOnMainThread:@selector(startConnection) 
                        withObject:Nil 
                     waitUntilDone:NO];

如果您想让您的委托在另一个线程上被调用,请尝试:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
    [connection scheduleInRunLoop:currentRunLoop forMode:NSRunLoopCommonModes];
    [connection start];
    [currentRunLoop run];
});

【讨论】:

    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多