数据请求 -开源库ASI的使用





#pragma mark - 同步请求



// 1.初始化一个url

NSURL * url = [NSURL URLWithString:@"http://ss14.sinaimg.cn/large/48c2531d4de01d9df70dc"];

// 初始化一个请求对象,等待时间60s 请求方式get请求

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

[request setTimeOutSeconds:60];

[request setRequestMethod:@"GET"];



/*



// 2.发送同步请求

[request startSynchronous];



// 3. 获取数据

NSData * imagedata = request.responseData;



// 4. 保存图片到本地

NSString * filepath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/432.jpg"];

[imagedata writeToFile:filepath atomically:YES];



*/



#pragma mark - 异步请求

//设置请求的block





/* 设置缓存 */



// 1. 创建一个缓存对象

ASIDownloadCache * cache = [[ASIDownloadCache alloc] init];



// 2. 设置缓存路径

[cache setStoragePath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];



// 3. 设置缓存策略 本地有就取本地 本地没有就去网络下

[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];



// 4. 把缓存对象付给 request

[request setDownloadCache:cache];



// 5. 设置request缓存的声明周期

[request setCacheStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];

//ASICacheForSessionDurationCacheStoragePolicy = 0, 清除上次绘画的缓存

//ASICachePermanentlyCacheStoragePolicy = 1 永久缓存,程序下次启动 缓存仍然在







// 1.获取成功保存数据

[request setCompletionBlock:^{

// 保存图片到本地

NSString * filepath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/4998.jpg"];

[request.responseData writeToFile:filepath atomically:YES];

}];



// 2. 获取失败

[request setFailedBlock:^{

NSLog(@"请求失败");

}];



// 3. 发送异步请求

[request startAsynchronous];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值