OC下载网页

#import "ViewController.h"

typedef void (^loginBlock)();
static NSOperationQueue *queue;

@interface ViewController ()

@property (nonatomic, weak)UIActivityIndicatorView *indicator;
- (IBAction)btnClick:(id)sender;
@property (weak, nonatomic) IBOutlet UITextView *content;

@property (nonatomic, copy)loginBlock loginBlock;


@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    void (^loginBlock)();
    loginBlock = ^{
        NSLog(@"hello world");
    };
    self.loginBlock = loginBlock;
    // 调用
    loginBlock();
    
    UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.indicator = testActivityIndicator;
    
    testActivityIndicator.center = CGPointMake(100.0f, 100.0f);//只能设置中心,不能设置大小
    
    [self.view addSubview:testActivityIndicator];
    
    // 声明变量
    
    
    //    [testActivityIndicator startAnimating]; // 开始旋转
    // Do any additional setup after loading the view, typically from a nib.
}



- (IBAction)btnClick:(id)sender {
    
     self.loginBlock();
    /**
     *  原代码块1
     */
    self.indicator.hidden = NO;
    [self.indicator startAnimating];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        /**
         *  原代码2
         */
        NSURL *url = [NSURL URLWithString:@"http://www.youdao.com"];
        NSError *error;
        NSString *data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        if (data!=nil) {
            /**
             *  原代码3
             */
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.indicator stopAnimating];
                self.indicator.hidden = YES;
                self.content.text = data;
            });
        } else {
            NSLog(@"error");
        }
        
    });
    
#if 0

    [self.indicator startAnimating];
    
    queue = [[NSOperationQueue alloc] init];
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];
    [queue addOperation:op];
#endif
}

#if 0
- (void)download {
    
    NSURL *url = [NSURL URLWithString:@"http://www.youdao.com"];
    NSError *error;
    
    NSString *data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (data != nil) {
        [self performSelectorOnMainThread:@selector(download_completed:) withObject:data waitUntilDone:NO];
    } else {
        NSLog(@"error when download:%@", error);
    }
}

- (void) download_completed:(NSString *) data {
    NSLog(@"call back");
    [self.indicator stopAnimating];
    self.indicator.hidden = YES;
    self.content.text = data;
    
}
#endif

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(多线程,下载,Class,ios开发)