NSURLConnection sendAsynchronousRequest - 与HTTPS通信

时间:2012-10-14 17:36:48

标签: iphone ios cocoa-touch

正在处理从iPhone获取图片的iPhone应用程序。我正在使用'NSData dataWithContentsOfUrl]&它工作得很好。 但是,正如您可能已经猜到的那样,请求是同步的。

我希望请求是异步的。所以,我尝试使用NSURLConnection的sendAsynchronousRequest()调用。但是这会在方法'didFailWithError'中返回以下错误:

  

错误域= kCFErrorDomainCFNetwork代码= 310“出现问题   与安全Web代理服务器(HTTPS)通信。

有人可以帮忙吗?

这是我的NSURLConnection代码段:

NSURL *url = [NSURL URLWithString:notePicUrl];

            NSURLRequest *urlRequest = [NSURLRequest  requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
            //NSOperationQueue *queue = [[NSOperationQueue alloc] init];

            NSURLConnection* _connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];
            self.port = [NSPort port];                                                                                                       
            self.runLoop = [NSRunLoop currentRunLoop];                                                                                       
            [self.runLoop addPort:self.port forMode:NSDefaultRunLoopMode];
            [_connection scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
            [_connection start];
            while (self.finished != YES ) {
                [self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 0.1]]; 
            }
            [self.runLoop removePort:[self port] forMode:NSDefaultRunLoopMode];
            [_connection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

NSURLConnectionDelegate方法(尚未实现;只是先测试一下,看它是否有效)......

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
    NSLog(@"didReceiveResponse");
    //_data = [[NSMutableData alloc] init]; // _data being an ivar
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    NSLog(@"didReceiveData");
    //[_data appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"didFailWithError %@", [error description]);
    // Handle the error properly
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    NSLog(@"connectionDidFinishLoading");
    //[self handleDownloadedData]; // Deal with the data
}

1 个答案:

答案 0 :(得分:0)

我刚修好了;我尝试使用简单的代码行:

[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

然后处理Delegate方法中的数据。早些时候,它试图在一个单独的线程中运行。这很好用&是异步的。