2012-01-23 6 views
1

私はNSURLConnectionを使ってサーバーにアクセスしています。定期的にリクエストする方法を説明できるサンプルコードが必要ですか? viewDidLoadメソッドにNSURLConnectionインスタンス変数を追加することをお勧めしますか?非同期NSURL接続をサーバーに定期的に送信する方法に関するサンプルコードはありますか?

- (void)viewWillAppear:(BOOL)animated 
    { 
     [super viewWillAppear:animated]; 
     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"myurl/test.csv"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0]; 

     NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

     if(connection){ 
      label.text = @"connecting..."; 
     }else{ 
     // 
     } 


    } 

-(void)connection :(NSURLConnection *) connection didReceiveData:(NSData *)data{ 
    [self viewWillAppear:TRUE]; 
     response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(response); 
     } 

次のNSTimerメソッドを使用して、viewWillAppearメソッドを呼び出しました。

- (void)checkURLRequest 
    { 
    [self setProgressTimer:[NSTimer 
         scheduledTimerWithTimeInterval:(1.0f/30.0f) 
         target:self 
         selector:@selector(viewWillAppear:) 
         userInfo:self 
         repeats:TRUE]]; 
    } 

    - (void)setProgressTimer:(NSTimer *)theTimer 
    { 
    [_progressTimer invalidate]; 
    _progressTimer = theTimer; 
    } 
+0

のviewDidLoadはクラスではありません...あなたはそこNSURLConnnectionのIVARを置くことによって何を意味するのですか? –

+0

私の間違いでした申し訳ありません。編集 –

+0

np。サンプルコードを追加しました。 –

答えて

4

あなたは、この動作を実現するためにNSTimerを設定することができます

- (id) init 
{ 
    // regular [super init], etc. etc. 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(sendRequest) userInfo:nil repeats:YES]; 
    // other custom initialization continues 
    return self; 
} 

- (void) sendRequest 
{ 
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/service.php"]] delegate:self]; 
} 

// and implement NSURLConnectionDelegate methods here 
+0

これらの方法はどこに置かなければならないのですか?それはviewWillAppearでそれを行うことをお勧めですか? –

+0

viewWillAppearは複数回呼び出されます。私は明示的に書いています:最初はinitに入り、もう1つは任意のメソッド名です。どのクラスのクラスを持っているのかはわかりませんが、おそらくメインビューのコントローラーにあります。 –

+0

助けてくれたらどうぞよろしくお願いします。ありがとうございました。 –

関連する問題