프로그래밍 놀이터/iOS

[ios] AFNetworking 을 이용하여 File download start, pause, resume, stop 시키기

돼지왕 왕돼지 2018. 2. 21. 08:30
반응형

[ios] AFNetworking 을 이용하여 File download start, pause, resume, stop 시키기



static NSString* const kZipURL = @"http://download.thinkbroadband.com/200MB.zip";


@interface ViewController (){

    AFHTTPRequestOperation* _operation;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    [self initHTTPRequestOperation]; // 더 적합한 position 으로 옮겨야 하지만, 개념만 보여주기 위해.

}


- (IBAction)onStartClicked:(id)sender {

    [_operation start];

}


- (IBAction)onPauseClicked:(id)sender {

    [_operation pause];

}


- (IBAction)onResumeClicked:(id)sender {

    [_operation resume];

}


- (IBAction)onStopClicked:(id)sender {

    [_operation cancel];

}


-(void)initHTTPRequestOperation{

    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *filePath = [[docPaths lastObject] stringByAppendingPathComponent:@"test.zip"];


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kZipURL]];

    _operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];

    _operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

    [_operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

        NSLog(@"MMM %lld / %lld", totalBytesRead, totalBytesExpectedToRead);

    }];


    [_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

          NSLog(@“MMM Success”);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

          NSLog(@“MMM Fail %@”, error);

        }];

}


@end




반응형