IOS/Objective-C: 发送同步请求登录

IOS/Objective-C: Send Synchronous request for login

您好,我一直在发送一个带有异步请求的登录(因为通常建议尽可能使用异步)但我现在想让它同步以便在我收到响应时更好地控制。

有人可以建议如何将下面的异步代码更改为同步代码吗?

感谢任何建议:

 NSURL *url = [NSURL URLWithString:@"http://~/login.php"];
    NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
    [rq setHTTPMethod:@"POST"];
    NSData *jsonData = data;
    [rq setHTTPBody:jsonData];
    [rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
//Want to change to a synchronous request
    [NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *data, NSError *err) {
        if (err) {
            NSLog(@"Error%@",err);
        } else {
            NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                      NSNumber *idResponse = jsonResults[@"response"][@"userid"];
            if (![idResponse isKindOfClass:[NSNull class]]) {
                NSInteger userid = [idResponse integerValue];
            }
            }
          dispatch_async(dispatch_get_main_queue(), ^{
                //back in main queue to use results of login.

            });
        }
    }];
}

根据 Apple 的说法,有一个名为

的同步请求功能
+ sendSynchronousRequest:returningResponse:error:

而且,根据 Apple 的说法,您永远不应该在 GUI 应用程序的主线程中使用它(在下面的 link 中解释)

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/clm/NSURLConnection/sendSynchronousRequest:returningResponse:error:

您发布的 Async,在使用

完成调用后最终返回到主线程
dispatch_get_main_queue()

我建议对iOS如何使用 GCD 管理多线程进行一些研究

我觉得你运气不好。

A​​pple 已弃用 NSURLConnection 中的几乎所有方法。我们应该开始使用 NSURLSession 来代替,那只是异步的。

外卖是"if you're using synchronous networking, you're doing it wrong."

我认为您应该硬着头皮进行重构。我所做的是创建我自己的方法,它接受一个完成块,NSURLSession 中的完成块调用我的方法完成块(从主线程使事情变得简单。)