您的位置:首页 > 其它

系统缓存NSURLCache

2016-05-27 16:21 567 查看
//

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: