【问题标题】:iOS NSURLConnection didReceivedData more than one taskiOS NSURLConnection didReceivedData 不止一项任务
【发布时间】:2014-07-24 03:38:39
【问题描述】:

我在 iOS 中有很大的问题。 由于某些原因,我必须使用异步,因为我想传递 SSL 错误。 因此,我使用 NSURLconnection 并在 didReceiveData 中从 Web 服务器获取响应数据。 当我只将一个 url 发布到服务器时,它工作得很好。

但我的问题是:如果我需要同时向服务器发布 2 或 3 个不同的 url! 然后我在didReceiveData中收到响应数据,我想会很混乱! 我怎么知道哪个响应的数据属于哪个帖子任务? 有没有人可以帮助我?请..谢谢。

【问题讨论】:

  • 使用每个委托方法的NSURLConnection参数来知道响应是针对哪个连接的。
  • rmaddy,你能给我每个委托的 NSURLConnection 参数的示例代码吗?我需要编写不同的 didReceiveData 吗?

标签: ios nsurlconnectiondelegate


【解决方案1】:

为此,您必须在 NSURLConnection 的委托方法中检查您的 connection。 & 使用两个不同的 resposeData。

示例: 这里有两个连接connSend & connRecieve

如果使用 connSend

NSURL *url = // Your URL
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
connSend=[[NSURLConnection alloc] initWithRequest:requestObj delegate:self];

对于其他连接

NSURL *url = // Your URL
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
connRecieve =[[NSURLConnection alloc] initWithRequest:requestObj delegate:self]




- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (connection==connSend) {
        responseSend = [[NSMutableData alloc]init];
        [responseSend setLength:0];
    }
    else{
        responseData = [[NSMutableData alloc]init];
        [responseData setLength:0];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (connection==connSend) {
        [responseSend appendData:data];
    }
    else{
        [responseData appendData:data];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if (connSend==connection) {
       NSLog(@"Error in sending");
    }
    else{
        NSLog(@"Error in receiving");
    }
}

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

    if (connection==connSend) {
    // Connection send.
    }
    else{
    // Connection recive
     }

}

最好你可以创建不同的类来获得不同的服务器响应,

【讨论】:

  • connSend 写在:NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:connSend];委托:自我 => 委托:connSend 对吗?谢谢
  • 使 NSURLConnection 全局化。
  • NSURLConnection *connSend1 = [[NSURLConnection alloc] initWithRequest:request delegate:self]; NSURLConnection *connSend2 = [[NSURLConnection alloc] initWithRequest:request delegate:self];对?谢谢
  • 是的,但是在 .h 文件中声明 connSend1 & connSend2。所以你可以在委托方法中比较它,
  • 我是初学者!请详细...对不起
猜你喜欢
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多