2012-03-29 60 views
0

我试图执行一个asynchornus请求。我做我的研究,这是我最好的,但代码是充满了我不找创建一个异步请求

NSURL *url2 = [NSURL URLWithString:@"www.google.com"]; 

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url2]; 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    { 
     if ([data length] > 0 && error == nil) 
      [delegate receivedData:data];//i get the error here use of undeclared identifier 'delegate' ,when I put self insead I receive the error : no visible @interface for "my class name" declares the selector "received data" 
     else if ([data length] == 0 && error == nil) 
      [delegate emptyReply];//same error here 
     else if (error != nil && error.code == ERROR_CODE_TIMEOUT) //the error here is "use of undelcared identifier ERROR_CODE_TIMEOUT 
      [delegate timedOut];//error here is save as the first one 
     else if (error != nil) 
      [delegate downloadError:error];//error here is save as the first one 
    }]; 

的解决方案,我已经在我的.h文件中添加NSURLConnectionDelegate错误的

有人可以告诉我什么是错误?

感谢

+0

能否请您粘贴输出? – 2012-03-29 04:39:30

回答

1

我对这种方法没有多少经验,但是这个例子很有效。我将此发送到我的服务器以测试获取应用内购买的产品信息。你可以把更多的东西放进去,就像你发布的那样,以测试不同的可能结果,但这应该让你开始。我不确定为什么你发布的这个存根引用了一个委托 - 块方法的要点(或者其中一个要点)是能够在没有委托的情况下完成这些事情。

- (void)makeConnection { 
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:kServerPath] 
              cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
             timeoutInterval:5]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
[NSURLConnection sendAsynchronousRequest:theRequest queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error) { 
    NSLog(@"%@, %@ %@",theResponse.suggestedFilename,theResponse.MIMEType,theResponse.textEncodingName); 
    if (theData != nil && error == nil) { 
     NSArray *productArray = [NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingMutableContainers error:nil]; 
     NSLog(@"%@",productArray); 
    }else{ 
     NSLog(@"%@",error.localizedDescription); 
    } 
}]; 

}

0

我觉得它更容易只是 - initWithRequest:代表:根据需要和实现委托方法。你至少要

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

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

。有些代码请参见http://developer.apple.com/library/ios/#samplecode/SimpleFTPSample/Listings/URLGetController_m.html。请注意,接收数据是为增量块调用的。您可能希望跟踪属性中的总数据并在数据到达时追加数据。除此之外,你可以抛出错误处理和认证,但这应该让你开始。