网络数据解析及加载本地 缓存封装
2015-09-09 21:55
543 查看
#import <Foundation/Foundation.h>
@interface Person :
NSObject
//作用: 封装网络请求
+ (void)getDataWithURL:(NSString *)str comletion:(void(^)(NSData *data))block;
@end
+ (void)getDataWithURL:(NSString *)str comletion:(void(^)(NSData *data))block
{
//1. 创建请求
NSString *urlStr = [str
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL
URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];
request.HTTPMethod =
@"get";
//2.发送请求到服务器(异步)
[NSURLConnection
sendAsynchronousRequest:request queue:[NSOperationQueue
mainQueue]completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
//3.处理数据
if (data ==
nil) {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)lastObject];
NSString *strPath = [path
stringByAppendingPathComponent:@"1.xml"];
data = [NSData
dataWithContentsOfFile:strPath];
NSLog(@"str:%@",data);
block(data);
}
else{
block(data);
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)lastObject];
NSString *strPath = [path
stringByAppendingPathComponent:@"1.xml"];
[data writeToFile:strPath
atomically:YES];
}
}];
}
@interface Person :
NSObject
//作用: 封装网络请求
+ (void)getDataWithURL:(NSString *)str comletion:(void(^)(NSData *data))block;
@end
+ (void)getDataWithURL:(NSString *)str comletion:(void(^)(NSData *data))block
{
//1. 创建请求
NSString *urlStr = [str
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL
URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];
request.HTTPMethod =
@"get";
//2.发送请求到服务器(异步)
[NSURLConnection
sendAsynchronousRequest:request queue:[NSOperationQueue
mainQueue]completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
//3.处理数据
if (data ==
nil) {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)lastObject];
NSString *strPath = [path
stringByAppendingPathComponent:@"1.xml"];
data = [NSData
dataWithContentsOfFile:strPath];
NSLog(@"str:%@",data);
block(data);
}
else{
block(data);
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)lastObject];
NSString *strPath = [path
stringByAppendingPathComponent:@"1.xml"];
[data writeToFile:strPath
atomically:YES];
}
}];
}