不调用NSURLConnection Asynchrone委托方法

时间:2014-10-06 15:12:47

标签: ios asynchronous nsurlconnection nsurl

我正在开发WebService。我正在使用NSURL开发我的iOS客户端。我向服务器发送异步请求并获取数据(逐包)。我的请求被正确发送到服务器,但没有调用委托方法。

@implementation WebServiceClientCom

...

-(void) connectionDidFinishedLoading:(NSURLConnection*) in_urlConnection
{
    int i=0;
}

-(void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response

{
    NSLog(@"YOUPI");
    int i=0;
}

-(void) connection:(NSURLConnection*) connection didReceiveData:(NSData *)data

{
    NSLog(@"YOUPI");
    int i=0;
}

-(void) connection:(NSURLConnection*) connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;

{
    NSLog(@"YOUPI");
    int i=0;
}

-(void) connection: (NSURLConnection*)connection didFailWithError: (NSError*) error
{
    NSLog(@"%@", error);
    int i=0;
}

-(void) sendAsynchronousRequest: (NSData*) in_dataToSend
{
    _oUrlRequest.HTTPBody = in_dataToSend;
    _oUrlConnection = [[NSURLConnection alloc] initWithRequest:_oUrlRequest delegate:self startImmediately:YES];
    if(!_oUrlConnection)
        NSLog(@"Connection failed");
    else
        NSLog(@"Connection succeeded");
}

@end

我不明白这是什么问题?为什么?在哪里?

请帮帮我:)。

3 个答案:

答案 0 :(得分:0)

您可能忘记设置委托,请确保不将nil作为参数传递:

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

有关详细信息,请查看using NSURLConnection

<强>更新

尝试:

_oUrlConnection = [[NSURLConnection alloc] initWithRequest:_oUrlRequest delegate:self  startImmediately:NO];
[_oUrlConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[_oUrlConnection start];

也许它正在另一个线程中执行。

答案 1 :(得分:0)

如果您没有强烈引用WebServiceClientCom对象,则可能会在收到回复之前将其丢弃。尝试使用此类实例,而不是:

@interface MyClass
@property (strong) WebServiceClientCom *myCommunicator;
/* ... */
@end

@implementation MyClass
- (void)communicate:(NSData *)data {
  if (!self.myCommunicator) {
    self.myCommunicator = [[WebServiceClientCom alloc] init];
  }
  [self.myCommunicator sendAsynchronousRequest:data];
}
@end

答案 2 :(得分:0)

好的,Thansk全部,我在连接后忘了[[NSRunLoop currentRunLoop] run] [[NSURLConnection alloc] intiWithRequest:request delegate:self startImmediately:YES]

但是,我还有另一个问题:我怎么能退出这个循环,所以异步方法??? ^^