0

我正在尝试实现异步请求。我做了我的研究,这是我得到的最好的,但是代码充满了我找不到解决方案的错误

   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
    }];

我已NSURLConnectionDelegate在我的 .h 文件中添加

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

谢谢

4

2 回答 2

1

我对这种方法没有太多经验,但这个例子有效。我将此发送到我的服务器以测试获取应用内购买的产品信息。您可以将更多 else-if 放入其中,就像您发布的那样,以测试不同的可能结果,但这应该可以帮助您入门。我不确定为什么您发布的存根引用了委托——块方法的要点(或要点之一)是能够在没有委托的情况下做这些事情。

- (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);
    }
}];

}

于 2012-03-29T05:01:00.943 回答
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。请注意,对于增量块调用确实接收数据。您可能希望跟踪属性中的总数据并在数据到达时附加数据。除此之外,您可以进行错误处理和身份验证,但这应该可以帮助您入门。

于 2012-03-29T03:36:13.220 回答