LoginSignup
11
13

More than 5 years have passed since last update.

NSURLConnection sendAsynchronousRequestをリトライ機能付きでリクエストする

Last updated at Posted at 2013-02-14

今回も線形反復のサンプルです。

NSURLConnectionを何度かリトライ込みで記述してみます。

@interface DownloadUtility : NSObject
+ (void)downloadAndRetryWithURL:(NSURL *)url retryCount:(int)retryCount completion:(void(^)(NSURLResponse *response, NSData *data))completion failue:(void(^)())failure;
@end
@implementation DownloadUtility
+ (void)downloadAndRetryWithURL:(NSURL *)url retryCount:(int)retryCount completion:(void(^)(NSURLResponse *response, NSData *data))completion failue:(void(^)())failure
{
    completion = [completion copy];
    failure = [failure copy];

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if(error)
         {
             if(retryCount > 0)
             {
                 NSLog(@"retry");
                 [DownloadUtility downloadAndRetryWithURL:url
                                               retryCount:retryCount - 1
                                               completion:completion
                                                   failue:failure];
             }
             else
             {
                 if(failure)
                     failure();
             }
         }
         else
         {
             if(completion)
                 completion(response, data);
         }
     }];
}
@end


    //呼び出し側
    [DownloadUtility downloadAndRetryWithURL:[NSURL URLWithString:@"http://www.google.co.jp"]
                                  retryCount:5
                                  completion:^(NSURLResponse *response, NSData *data)
    {
        NSLog(@"complete!");
    } failue:^{
        NSLog(@"failure...");
    }];

呼び出し側が非常にシンプルになります。

簡単なフローチャートです。
ただこのコードはフローチャートとの乖離が激しいです
https://cacoo.com/diagrams/wveKhJQz9S00oIMG

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13