当网络连接速度较慢时,应用程序冻结,因为在应用程序启动时会发生 POST API 调用.下面是我的连接管理器代码,Obj



//下面是我用来执行简单httpPOST的代码。但是应用程序在启动时挂起 应用程序启动时 在启动画面并崩溃 .我正在应用程序委托中的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,它们开箱即用。

首先设置请求的timeoutInterval。 如果您的请求需要更多时间,则必须停止 API 调用并使用正确的错误消息通知用户。

例如:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];

不要使用Synchronised Request.它将阻塞您的主线程。

如果您的网络速度较慢或服务器没有响应,那么您的应用将需要更多时间来加载。这对用户体验不利。

请记住,应用的加载时间是您给用户留下深刻印象的第一次机会。

使用NSURLConnectionAsynchronised Request。处理 api 完成块中的响应。

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSString *resSrt = [[NSString alloc]initWithData:data 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");
}
}];

根据需要更改queue:[NSOperationQueue mainQueue]参数。

queue->一个 NSOperationQueue,处理程序块将在其上 被派遣。

最新更新