GCD異步下載網頁功能

在不使用GCD下載情況:


- (void)btnPress:(id)sender{

    self.labContent.text = @"";

    self.indicator.hidden = NO;

    [self.indicator startAnimating];

    

    NSOperationQueue *que = [[NSOperationQueue alloc] init];

    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];

    [que addOperation:op];

    self.queue = que;

}


- (void)download{

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    NSError *error;

        NSString *strData = [NSString stringWithContentsOfURL:url

                                                     encoding:NSUTF8StringEncoding

                                                        error:&error];

    if (strData && strData != nil) {

        [self performSelectorOnMainThread:@selector(download_completed:) withObject:strData waitUntilDone:NO];

    }else {

        NSLog(@"error when download:%@", error);

    }

}


- (void)download_completed:(NSString *)strData{

    NSLog(@"call back");

    [self.indicator stopAnimating];

    self.indicator.hidden = YES;

    self.labContent.text = strData;

}



使用GCD後代碼簡潔多了:


- (void)btnPress:(id)sender{

    self.labContent.text = @"";

    self.indicator.hidden = NO;

    [self.indicator startAnimating];

  

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

        NSError *error;

        NSString *strData = [NSString stringWithContentsOfURL:url

                                                     encoding:NSUTF8StringEncoding

                                                        error:&error];


        if (strData && strData != nil) {

            dispatch_async(dispatch_get_main_queue(), ^{

                [self.indicator stopAnimating];

                self.indicator.hidden = YES;

                self.labContent.text = strData;

            });

        }else {

            NSLog(@"error when download:%@", error);

        }

    });

}



GCD參考資料:http://mobile.51cto.com/iphone-403490.htm


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章