系统缓存NSURLCache

//
// NetWorkHandle.m
// NetWork
//
// Created by 李元喜on 16/5/5.
// Copyright (c) 2016年 李元喜. All rights reserved.
//

#import "NetWorkHandle.h"
#define DebugLog(...) NSLog(__VA_ARGS__)

@implementation NetWorkHandle

+ (void)getDataWithURLString:(NSString *)string
compare:(MyBlock)block
{

NSURLCache *cache = [NSURLCache sharedURLCache];
[cache setMemoryCapacity:1*1024*1024];

// 对地址做一次UTF-8的转码,防止参数里面有中文
NSString *urlString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (data != nil) {
//判断是否进行了缓存
NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
if (request) {
DebugLog(@"进行了缓存");
}else{
DebugLog(@"没有进行缓存");
}
// 因为不确定数据的类型,所以用id 泛型指针去接收
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
block(object);
}
}];
}

+ (void)postDataWithURLString:(NSString *)string
andBodyString:(NSString *)bodyString
compare:(MyBlock)block
{
NSString *urlString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data != nil) {
// 因为不确定数据的类型,所以用id 泛型指针去接收
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
block(object);
}
}];

}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值