ios - 无法从完成处理程序进行网络调用?

标签 ios objective-c iphone xcode ipad

我正在尝试访问用户表单电话的联系人。所以我正在使用完成处理程序。因此,当应用程序尝试访问用户的联系人时,它会显示警报并请求允许联系人的权限。当用户按“确定”按钮。

enter image description here

然后执行一个 block ,那时我进行网络调用。虽然调用了该函数,但永远不会调用委托(delegate),也永远不会收到响应。

ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
    {

        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            // First time access has been granted, add the contact
            NSLog(@"access contact");
           [self sample];

        });
          NSLog(@"after sccess contact");

    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
    {
        // The user has previously given access, add the contact
        NSLog(@"previous access");
    }
    else
    {
        // The user has previously denied access
        // Send an alert telling user to change privacy setting in settings app
        NSLog(@"send alert");
    }
    CFErrorRef error = NULL;

网络通话

-(void)sample
{
    NSLog(@"sample func called");
    // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    // Convert your data and set your request's HTTPBody property
    NSString *stringData = @"some data";
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    sampleConn= [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

最佳答案

试试这个

替换你的代码

[self sample];

dispatch_async(dispatch_get_main_queue(), ^{

    [self sample];
});

关于ios - 无法从完成处理程序进行网络调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645838/

相关文章:

ios - UIButton 在 UITableview 中不起作用

ios - 在横向启动时 UIView 大小变糟

ios - 在Xcode中运行应用程序时,如何通过mac传输屏幕和控制设备?

ios - 在 IntelliJ IDEA 中运行 iOS React Native 项目时如何指定设备

ios - Xcode 6 iPair Air 无法在设备上运行应用程序(操作系统版本)

ios - 有没有办法让两次点击手势识别器具有不同的点击次数

iphone - 具有线性渐变的 Chrome 文本效果提供锯齿状边缘

ios - 如何重新调整文字大小?

ios - 如何使用 ios-charts 创建游标

c++ - 生成的 Objective-C 接口(interface)中出现编译错误