如何解决NSURLError:网络连接丢失了?

时间:2015-11-24 06:41:23

标签: ios objective-c iphone xcode nsurlconnection

我正在开发一个应用程序,我在其中使用Web服务方法从服务器获取数据。

以下是我的代码。

responseData = [NSMutableData data];

    NSString *service = @"/getActivity.php";

    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
    NSString *urlLoc = [fileContents objectForKey:@"URL"];
    urlLoc= [urlLoc stringByAppendingString:service];

    loginUser = [[NSUserDefaults standardUserDefaults]valueForKey:@"username"];
    NSLog(@"%@",loginUser);

    NSLog(@"%@",selectUsername);
    // this is correct
    //NSString *requestStringg = [NSString stringWithFormat:@"{\"?username\"=\"%@\"&\"follower_username\"=\"%@\"}",loginUser,selectUsername];
    NSDate * date = [NSDate date];
    // NSLog(@"Date:%@",date);
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];

    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *date_str = [dateFormat stringFromDate:date];

    NSString *requestString = [NSString stringWithFormat:@"username=%@&follower_username=%@&follower_created_date=%@",loginUser,selectUsername,date_str];

    NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:urlLoc]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    postFollowUnfollowConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    NSLog(@"error :%@",error);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    if (connection == postNotificationConnection)
    {
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"%@",responseString);

     }

}

我的网络服务工作正常,但在第4次或第5次调用网络服务后,它会进入didFailWithError,向我显示以下错误。

enter image description here

我已经为这个错误尝试了所有可能的解决方案,但没有任何帮助我。此错误在iOS 8和iOS 9中生成。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

1)iOS 8问题但可以使用

解决
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

而不是

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

2)其他解决方案是增加RequestTime:

[request setTimeOut:180];