【问题标题】:NSURLConnection Delegate methods not getting called after two times两次后未调用 NSURLConnection 委托方法
【发布时间】:2014-07-03 11:21:02
【问题描述】:

我正在使用 NSURLConnection 向服务器发送请求,它工作了 2 次,因为第三次它不工作,delegates 没有被调用。我在调试过程中发现connectionShouldUseCredentialStorage方法在初始时被调用,第三次没有被调用,其余的方法也没有被调用。

这是我的代码:

    NSString *requestString = [NSString stringWithFormat:@"%@", [serviceParameters JSONFragment], nil];

    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    [request setHTTPBody:requestData];
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [NSMutableData data];
}


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


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    SBJSON *jsonParser = [[SBJSON new] autorelease];
    NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
    NSError *outError = nil;

    id result = [jsonParser objectWithString:jsonString error:&outError];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}


- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
    {
        return YES;
    }
    return NO;
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return YES;
}

【问题讨论】:

  • 你试过在 NSURL 委托方法中设置断点吗?你也可以尝试增加超时时间。
  • 能否检查返回的NSURLConnection是否不是nil,if([NSURLConnection connectionWithRequest:urlRequest delegate:self] != nil) { NSLog(@"connectgion started"); }
  • 您是从主线程运行它,还是从连接到运行循环的线程运行它?根据文档:“委托方法在调用此方法的同一线程上调用。要使连接正常工作,调用线程的运行循环必须在默认运行循环模式下运行。”
  • @user2071152 我尝试使用断点并尝试使用超时 300 值,但无助于解决问题。
  • @satheeshwaran:我试过你的代码,它显示连接已启动。 NSURLConnection 不为零。

标签: ios iphone ios7 nsurlconnection nsurlconnectiondelegate


【解决方案1】:

在.h中

NSMutableData * data;
NSURLConnection *connection;

同样添加添加

在.m

-(void) startConnection
{
    NSString *requestString = [NSString stringWithFormat:@"http://md5.jsontest.com/?text=Pushkraj"];

    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:60.0];


    data = [NSMutableData dataWithCapacity:0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    [request setHTTPBody:requestData];
    connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [NSMutableData data];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
    [data appendData:aData];
    NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"dataDict : %@",dataDict);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error : %@",error);
}

在 viewDidLoad 或 UIButton Click 上随处调用 [self startConnection];

【讨论】:

    【解决方案2】:

    您忘记开始连接了。您没有保存对 NSURLConnection 的引用以启动连接。所以替换最后一行

    [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    

    有了这个

    NSURLConnection *cn =[NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [cn start];
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      相关资源
      最近更新 更多