博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Get异步请求
阅读量:7087 次
发布时间:2019-06-28

本文共 1768 字,大约阅读时间需要 5 分钟。

1: 使用代理

        //1.delegate

        //创建url
     NSURL *url = [[NSURL alloc] initWithString:@"http:"];
//     创建request
     NSURLRequest *urlRequesr = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
//     发送异步请求
//     异步请求不知道什么时候获取到数据,delegate这种模式来创建,当获取到数据后,会自动调转到代理方法中
     [NSURLConnection connectionWithRequest:urlRequesr delegate:self];

#pragma mark - NSURLConnectionDataDelegate

    //请求出现错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}
//- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
//{
//    
//}
    //请求收到回应(可以认为请求开始)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", response);
    self.mData = [NSMutableData data];
     
}
    //请求获取到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%@", data);
        //网络上的数据以包得形式,一个包一个包得传递过来,需要把收到包数据整合到一起
    [_mData appendData:data];
}
    //请求完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [UIImage imageWithData:_mData];

    self.view.backgroundColor = [UIColor colorWithPatternImage:image];

}

2: 使用Block

  NSURL *url = [NSURL URLWithString:@""];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@", data);
        self.myData = data;
        [self readData];
    }];
- (void)readData {
    UIImage *image = [[UIImage alloc] initWithData:_myData];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
}

 

转载于:https://www.cnblogs.com/tian-sun/p/4310511.html

你可能感兴趣的文章
Win7添加Lookback接口
查看>>
iOS UIViewController 应用要点
查看>>
Centos ssh登录慢问题的解决办法
查看>>
centos6.3下haproxy+apache配置笔记
查看>>
InfluxDB学习笔记3---Chronograf
查看>>
我的友情链接
查看>>
zabbix系列之使用ansible批量部署zabbix客户端(二)
查看>>
Ansible简介
查看>>
开源社交系统---ThinkSNS V4.5直播版上线,PC端安装指南说明
查看>>
DEDECMS 常见错误
查看>>
Cacti 备份与迁移
查看>>
zabbix 监控ElasticSearch
查看>>
Oracle日志查看
查看>>
Simplify Your Life With an SSH Config File
查看>>
fork, clone, add, commit, fetch, rebase, push流程测试
查看>>
exchange删除邮件
查看>>
Mysql索引总结
查看>>
5、分区格式化、压缩、挂载、解压 学习笔记
查看>>
Android Studio databinding找不到BR的问题
查看>>
排序算法------快速排序
查看>>