2012-03-29 118 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。請注意,接收數據是爲增量塊調用的。您可能希望跟蹤屬性中的總數據並在數據到達時追加數據。除此之外,你可以拋出錯誤處理和認證,但這應該讓你開始。