2012-03-29 30 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

を追加している誰かが私に言うことができますエラーは何ですか?必要に応じて、デリゲートメソッドを実装し:デリゲート:initWithRequest -

おかげで

+0

あなたの出力を貼り付けてくださいことはできますか? –

答えて

1

私はこの方法で多くの経験はありませんが、この例では機能します。私はこれをサーバーに送って、アプリ内購入のための製品情報をテストすることをテストしました。投稿したように、異なる可能性のある結果をテストするために、より多くのelse-ifを入れることができます。なぜあなたが投稿したスタブがデリゲートへの参照を持っているのか分かりません。ブロックメソッドのポイント(またはポイントの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

私はそれだけで行うには簡単です見つけます。あなたは、少なくとも

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

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

をお勧めします。いくつかのコードについては、 http://developer.apple.com/library/ios/#samplecode/SimpleFTPSample/Listings/URLGetController_m.htmlを参照してください。受信データはインクリメンタルブロック用に呼び出されたことに注意してください。おそらくプロパティの合計データを追跡し、到着時にデータを追加したいと思うでしょう。それ以外の場合は、エラー処理と認証をスローすることができますが、それは開始する必要があります。

関連する問題