创建异步请求

时间:2012-03-29 03:03:01

标签: objective-c nsurlconnection sendasync

我正在尝试实施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

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

由于

2 个答案:

答案 0 :(得分: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);
    }
}];

}

答案 1 :(得分:0)

我发现它更容易 - initWithRequest:delegate:并根据需要实现委托方法。你需要

- (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。请注意,为增量块调用接收数据。您可能希望跟踪属性中的总数据并在数据到达时附加数据。除此之外,你可以抛出错误处理和身份验证,但这应该让你开始。