NSURLConnection sendAsynchronousRequest:queue:completionHandler在iOS 4.3中不起作用 [英] NSURLConnection sendAsynchronousRequest:queue:completionHandler not working in iOS 4.3

查看:91
本文介绍了NSURLConnection sendAsynchronousRequest:queue:completionHandler在iOS 4.3中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用 [NSURLConnection sendAsynchronousRequest:请求队列:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response,NSData * data,NSError * error)。通过使用这个我的应用程序在iOS 4.3中终止,但它在iOS 5.0中运行良好。

I am using [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) in my app. By using this my app is terminated in iOS 4.3 but it is working fine in iOS 5.0.

如何在iOS 4.3中使用它可以帮助我。

How to use this in iOS 4.3 can any one help me.

推荐答案

这是一个适合我的完整实现。您可以随意重命名并在 NSURLConnection 上添加类别,或者只是将其作为您正在使用的类中的本地方法添加。

Here's a full implementation that works for me. Feel free to rename it and add as a category on NSURLConnection, or just add it as a local method in the class you're working in.

-(void)sendAsynchronousRequest:(NSURLRequest*)request queue:(NSOperationQueue*)queue completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler
{
    __block NSURLResponse *response = nil;
    __block NSError *error = nil;
    __block NSData *data = nil;

    // Wrap up synchronous request within a block operation
    NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
        data = [NSURLConnection sendSynchronousRequest:request 
                                     returningResponse:&response 
                                                 error:&error];
    }];

    // Set completion block
    // EDIT: Set completion block, perform on main thread for safety
    blockOperation.completionBlock = ^{

        // Perform completion on main queue
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            handler(response, data, error);
        }];
    };

    // (or execute completion block on background thread)
    // blockOperation.completionBlock = ^{ handler(response, data, error); };

    // Execute operation
    [queue addOperation:blockOperation];
}

编辑
我必须修改方法,因为我在完成块中进行了UIKit调用(例如更新标签等)。因此,在主线程上调用完成块实际上更安全一些。 (原始版本已注释掉)

EDIT I had to modify the method because I was making UIKit calls in my completion block (e.g. updating labels etc). So it's actually a bit safer to call completion block on the main thread. (original version commented out)

这篇关于NSURLConnection sendAsynchronousRequest:queue:completionHandler在iOS 4.3中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆