//下面是我用来执行简单 httpPOST 的代码。但是应用程序挂起在启动画面上的应用程序启动并崩溃。我正在 Appdelegate 中对 applaunch 进行 API 调用
- (NSDictionary *)postUserRegWithUrl:(NSString *)urlString andParams:(NSString *)paramString{
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)paramString,
NULL,
(CFStringRef)@"+",
kCFStringEncodingUTF8 ));
NSDictionary *responseDictionary;
NSError *err;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseProdURL,urlString]]];
NSData *data = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSLog(@"the data Details is =%@", request);
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"got response==%@", resSrt);
if(resSrt.length)
{
responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];
NSLog(@"Response dictionary formed is =%@", responseDictionary);
} else {
NSLog(@"failed to connect");
[self showAlertViewTitle:@"Please try later" withMessage:@"Something went wrong"];
}
return responseDictionary;
}
最佳答案
您不应该同步执行网络调用,尤其是在主线程上。使用 sendAsynchronousRequest
或只使用任何好的网络库,例如 AFNetworking,它们开箱即用。
关于ios - 当网络连接缓慢时应用程序卡住,因为 POST API 调用发生在应用程序启动时。下面是我的连接管理器代码,Objective-C,iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967982/