繁体   English   中英

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.

            });
        }
    }];
}

据苹果称,有一个名为“同步请求”的功能

+ sendSynchronousRequest:returningResponse:error:

而且,根据Apple的说法,您永远不要在GUI应用程序的主线程中使用它(在以下链接中进行了解释)

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管理多线程进行一些研究。

我觉得你不走运。

Apple已弃用NSURLConnection几乎所有方法。 我们应该开始改用NSURLSession ,那只是异步的。

得出的结论是“如果使用同步网络,那就错了。”

我认为您可能应该硬着头皮进行重构。 我要做的是创建自己的带有完成块的方法,NSURLSession中的完成块调用我的方法完成块(从主线程开始,使事情变得简单)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM