objective-c - 检查 NSRunLoop 并使用适当的 NSURLConnection 方法

标签 objective-c cocoa foundation

我正在做一个个人项目,昨晚遇到了 NSURLConnection 的异步特性。我正在构建一个将与 restful api 接口(interface)的库。我期待在 Foundation 命令行工具和 Cocoa 应用程序中重用这个库。

有没有一种方法可以检查 runloop 是否可用于调用同步方法,如果是,则发送同步请求(如果在命令行工具中使用)。

或者,有没有办法始终使用异步方法,但强制应用程序在异步请求完成之前不退出?

我注意到了 this但我宁愿不必调用在图书馆外运行。

感谢您的帮助

最佳答案

Alternately, is there a way to always use the asynchronous method but force the application to not exit until the async request has finished?

简单易行:

int main(int argc, char *argv[])
{   
    // Create request, delegate object, etc.
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                                                                  delegate:delegate 
                                                          startImmediately:YES];
    CFRunLoopRun();
    // ...
}

我在这里使用 CFRunLoopRun() 是因为当代理确定连接已完成时可以稍后停止它:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // This returns control to wherever you called
    // CFRunLoopRun() from.
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
    CFRunLoopStop(CFRunLoopGetCurrent());
}

另一种选择是在 while 循环中使用 -[NSRunLoop runUntilDate:],并让委托(delegate)设置一个“停止”标志:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                                                              delegate:delegate 
                                                      startImmediately:YES];

while( ![delegate connectionHasFinished] ){
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1];
}

关于objective-c - 检查 NSRunLoop 并使用适当的 NSURLConnection 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106566/

相关文章:

iphone - 从另一个具有 objective-c 的函数更改我的函数的参数值

objective-c - 设置 MPMediaItem 的插图

objective-c - 切换暗模式时自定义 NSView 背景颜色不会改变

swift - `sum` 测量序列扩展

objective-c - NSPredicate 'OR' 基于 NSArray 键的过滤

ios - 像 UBER 一样在 Google map 上移动 GMSMarker

ios - 我收到 theos "cannot initialize a parameter of type"错误

cocoa - NSarray 发布

swift - "Bash like"NSURL 或 Foundation 路径的路径

ios - iPhone开发在dispatch_async中调用NSURLConnection并在mainRunLoop中读取didReceiveResponse