网络多线程 异步 同步处理

#import "UIImageView+WebCatch.h"

@implementation UIImageView (WebCatch)

- (void)setImageWithURL:(NSURL *)url
{
//    dispatch_queue_t queue = dispatch_queue_create("loadImage", nil);
//    dispatch_async(queue, ^{
//        NSData *data = [NSData dataWithContentsOfURL:url];
//        UIImage *image = [UIImage imageWithData:data];
//        //UI的操作主要放在主线程上去处理
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.image = image;
//        });
//    });
    
    //使用同步
    /*
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:url];
    [request setHTTPMethod:@"GET"]; //get 请求,没有请求体
    [request setTimeoutInterval:20];
    
    NSURLResponse *response;
    NSError *error;
    // 发送异步消息
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    UIImage *image = [UIImage imageWithData:data];
    self.image = image;
    */
    
    //异步请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:url];
    [request setHTTPMethod:@"GET"]; //get 请求,没有请求体
    [request setTimeoutInterval:20];
    //发送异步请求
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                               UIImage *image = [UIImage imageWithData:data];
                               //UI界面,同步主线程
                               dispatch_sync(dispatch_get_main_queue(), ^{
                                   self.image = image;
                               });
    }];
}

@end


#import <UIKit/UIKit.h>

@interface UIImageView (WebCatch) <NSURLConnectionDataDelegate>
- (void)setImageWithURL:(NSURL *)url;
@end

#import "ViewController.h"
#import "UIImageView+WebCatch.h"
#import "WebImageView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

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

- (void)loadView
{
    [super loadView];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 80, 40);
    [button setTitle:@"button" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onclick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)onclick
{
    for (int i = 0; i < 10; i ++){
//        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, i * 50, 50, 50)];
//        [imageview setImageWithURL:[NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=0ef89c67cf1b9d168ac79d61c7e6b58f/a71ea8d3fd1f4134ef340bc6241f95cad1c85e02.jpg"]];
//        [self.view addSubview:imageview];
//        [imageview release];
        
        WebImageView *imageview = [[WebImageView alloc]initWithFrame:CGRectMake(0, i * 50, 50, 50)];
        [imageview setURL:[NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=0ef89c67cf1b9d168ac79d61c7e6b58f/a71ea8d3fd1f4134ef340bc6241f95cad1c85e02.jpg"]];
        [self.view addSubview:imageview];
        [imageview release];
    }
}
@end

#import "WebImageView.h"

@implementation WebImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setURL:(NSURL *)url
{
    //异步处理
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setHTTPMethod:@"GET"];
    [request setURL:url];
    [request setTimeoutInterval:30];
    
    self.data = [NSMutableData data];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [UIImage imageWithData:self.data];
    self.image = image;
}
@end

#import <UIKit/UIKit.h>

@interface WebImageView : UIImageView <NSURLConnectionDataDelegate>{
    
}
@property (nonatomic, retain) NSMutableData *data;
- (void)setURL:(NSURL *)url;
@end



 来自网络

1、     同步GET请求

    //第一步,创建URL

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

    

    //第二步,通过URL创建网络请求

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)

      其中缓存协议是个枚举类型包含:

      NSURLRequestUseProtocolCachePolicy(基础策略)

      NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)

      NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)

      NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)

      NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)

      NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)

    //第三步,连接服务器

    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

    

    NSLog(@"%@",str);

2、同步POST请求

    //第一步,创建URL

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];

    //第二步,创建请求

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET

    NSString *str = @"type=focus-c";//设置参数

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    //第三步,连接服务器

    

    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

    

    NSLog(@"%@",str1);
3、异步GET请求

    //第一步,创建url

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

    //第二步,创建请求

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //第三步,连接服务器

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
4、异步POST请求

    //第一步,创建url

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];

    //第二步,创建请求

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [request setHTTPMethod:@"POST"];

    NSString *str = @"type=focus-c";

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    //第三步,连接服务器

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

5、异步请求的代理方法

//接收到服务器回应的时候调用此方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

    NSLog(@"%@",[res allHeaderFields]);

    self.receiveData = [NSMutableData data];

  

                              

}

//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [self.receiveData appendData:data];

}

//数据传完之后调用此方法

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",receiveStr);

}

//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法

-(void)connection:(NSURLConnection *)connection

 didFailWithError:(NSError *)error

{

    NSLog(@"%@",[error localizedDescription]);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值