Objective-C:不使用委托方法的异步/后台POST?

Nic*_*ard 7 cocoa-touch objective-c nsurlconnection ios

我需要对我的服务器进行一些POST调用,但我不需要阻止主线程.据我所知,NSMutableURLRequest并且NSURLConnection不是线程安全的,所以最好使用async方法NSURLConnection.

我的问题是,如何将它很好地打包到方法中,而不必使用委托方法?我更愿意这样做:

NSData *returnedData = [Utility postDataToURL:@"some string of data"];
Run Code Online (Sandbox Code Playgroud)

这是使用以下方法轻松完成的方法:

[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
Run Code Online (Sandbox Code Playgroud)

将一切保存在一个方法中,然后只是从中返回我的数据真是太好了!

有没有基于块的方法?当我需要为大约50个不同的调用编写方法并且每个调用需要使用相同的委托方法时,它就成了一个问题.我是以错误的方式来做这件事的吗?

这只需要适用于iOS5.

Tom*_*mmy 9

iOS 5添加sendAsynchronousRequest:queue:completionHandler:了我认为你想要的东西.我已将我的代码设置为使用该代码(如果可用),但是在后台GCD队列上执行同步提取并使用结果跳转到主线程(如果不可用).后者的功效会降低,但这只是为了保持传统的支持.

if([NSURLConnection respondsToSelector:@selector(sendAsynchronousRequest:queue:completionHandler:)])
{
    // we can use the iOS 5 path, so issue the asynchronous request
    // and then just do whatever we want to do
    [NSURLConnection sendAsynchronousRequest:request
        queue:[NSOperationQueue mainQueue]
        completionHandler:
        ^(NSURLResponse *response, NSData *data, NSError *error)
        {
            [self didLoadData:data];
        }];
}
else
{
    // fine, we'll have to do a power inefficient iOS 4 implementation;
    // hop onto the global dispatch queue...
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
        // ... perform a blocking, synchronous URL retrieval ...
        NSError *error = nil;
        NSURLResponse *urlResponse = nil;
        NSData *responseData =
            [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

        // ... and hop back onto the main queue to handle the result
        dispatch_async(dispatch_get_main_queue(),
        ^{
            [self didLoadData:responseData];
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

在生产代码中,您实际上会检查errors和HTTP响应代码(显然,从您的角度来看,服务器404响应可能与连接失败一样多).