ios - 当网络连接缓慢时应用程序卡住,因为 POST API 调用发生在应用程序启动时。下面是我的连接管理器代码,Objective-C,iOS

标签 ios objective-c

//下面是我用来执行简单 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/

相关文章:

iphone - json返回格式

ios - 使用 AutoLayout 将 UIView 隐藏在单元格内时,UITableViewCell 高度不合适

ios - UIViewContentModeCenter 添加填充

iphone - 如何在访问其他文本字段时使其他文本字段的键盘消失

iphone - 在 iTunes Connect 中,为什么分发证书已经存在?

ios - 如何避免在 NSNumberFormatter 中四舍五入

ios - UIAlertView元数据

iOS - 应用程序中的语言切换器 |未将语言设置为英语(美国)时不显示内容

objective-c - 自定义函数内的空数组

objective-c - 枚举并从 NSMutableArray 中删除特定对象