您的位置:首页 > 理论基础 > 计算机网络

ASIHTTPRequest框架使用(2)--发送异步请求

2014-05-09 13:37 627 查看
同步请求一般只是用在某个子线程中使用,而不在主线程中使用。异步请求的用户体验要比同步请求好,因此一般情况下异步请求用的多。

ASIHTTPRequest和ASIFormDataRequest两个请求类都可以发送异步请求。ASIFormDataRequest继承了ASIHTTPRequest异步请求方法,所以重点介绍ASIHTTPRequest的异步请求。

1、借助Delegate处理请求

- (void)startRequest

{

    NSString *strUrl = [[NSString alloc] initWithFormat:@"http://iosbook3.com/service/mynotes/webservice.php?                      email=%@&type=%@&action=%@",@"ios_yaoxinchao@163.com",@"JSON",@"query"];

    NSURL *url = [NSURL URLWithString:[strUrl URLEncodedString]];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    // 设置代理

    [request setDelegate:self];

    [request startAsynchronous];
}

#pragma mark - 代理方法 【默认调用的代理方法】

- (void)requestFinished:(ASIHTTPRequest *)request

{

    NSData *data = [request responseData];

    NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

    。。。。

}

- (void)requestFailed:(ASIHTTPRequest *)request

{

    NSError *error = [request error];

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

}

自定义回调方法:

- (void)startRequest

{

  ....

  // 自定义回调方法

  [request setDidFinishSelector:@selector(requestSuccess:)];

  [request setDidFailSelector:@selector(requestError:)];

}

- (void)requestSuccess:(ASIHTTPRequest *)request

{

    NSData *data = [request responseData];

    NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

    。。。。

}

- (void)requestError:(ASIHTTPRequest *)request

{

    NSError *error = [request error];

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

}

2、借助“Block”处理请求

- (void)startRequest

{

    NSString *strUrl = [[NSString alloc] initWithFormat:@"http://iosbook3.com/service/mynotes/webservice.php?                      email=%@&type=%@&action=%@",@"ios_yaoxinchao@163.com",@"JSON",@"query"];

    NSURL *url = [NSURL URLWithString:[strUrl URLEncodedString]];

    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 【1】

    [request setCompletionBlock:^{  // 设置成功完成时回调的Block

      NSData *data = [request responseData];

      NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

      。。。。

    }];

    [request setFailedBlock:^{  // 设置失败时回调的Block

      NSError *error = [request error];

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

    }];

    [request startAsynchronous];
}

【1】:__weak关键字的意思是ASIHTTPRequest对象是弱引用,不进行保持处理。目的是为了避免循环引用,造成内存泄露。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: