Objective C https请求在恢复主线程之前不等待响应

时间:2018-05-02 09:52:08

标签: ios objective-c https request ios-simulator

我的https请求存在问题(我认为这是问题)。我的问题是我有一个登录页面,询问我写的php Web服务,以检查尝试登录的用户是否可以这样做。 从Xcode启动应用程序时,Https请求正常工作但在苹果验证后我在App Store上发布了应用程序但不知何故,当我从App Store下载时,当我按下启动请求的登录按钮时应用程序冻结... < / p>

以下是我的请求代码:

NSString *url = [NSString stringWithFormat:@"https://cataloguetest.tabuleo.fr/Appmobile/webServ_firstCo.php?username=%@",username];
__block BOOL endOfBlock = false;
__block NSArray *ret;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:url]];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {

      NSString *strData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"Data received: %@", strData);
      NSError *jsonerror;
      NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonerror];
      NSString *validity =[jsonDict objectForKey:@"valid"];
      NSLog(@"get validity ok..");
      NSString *userInbase = [jsonDict objectForKey:@"usrIn"];
      NSLog(@"validity: %@",validity);
      NSLog(@"inBase: %@", userInbase);
      ret = @[validity ,userInbase];
      endOfBlock = true;
  }] resume];
while (!endOfBlock) {};

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好的,我设法获得了几乎完美的方法:

NSString *urlCheck = [NSString stringWithFormat:@"YOUR URL"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:urlCheck]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
  //do things with request's return
}] resume];

while(!postRequestReturned){

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate          distantFuture]];

}
NSLog(@"REQUEST resumed main thread");