iOS系统异步请求封装
2016-02-23 13:55
344 查看
在iOS开发中,我们经常会遇到网络请求的问题,AFNetworking是一个很不错的第三方库。当然iOS系统也有自己的网络异步请求类——NSURLConnection,虽然每次用的时候都要写代理,但是封装一下之后还是很好用的。封装的这个类除了完成异步网络请求,还加入了MD5的加密以及本地缓存。
// HttpDownLoadBlock.h
#import <Foundation/Foundation.h>
@interface HttpDownLoadBlock : NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
@property(nonatomic,strong)NSURLConnection * myConnection;
@property(nonatomic,strong)NSMutableData * data;
//文件生成路径
@property(nonatomic,copy)NSString * path;
//结果
@property(nonatomic,strong)NSArray * dataArray;
@property(nonatomic,strong)NSDictionary * dataDic;
@property(nonatomic,strong)UIImage * dataImage;
//需要block指针
@property(nonatomic,copy)void(^httpDownLoad)(BOOL , HttpDownLoadBlock *);
//外部调用的方法
-(id)initWithStrUrl:(NSString *)strUrl Block:(void(^)(BOOL,HttpDownLoadBlock *))a;
@end
// HttpDownLoadBlock.m
#import "HttpDownLoadBlock.h"
#import "MyMD5.h"
#import "NSFileManager+Method.h"
@implementation HttpDownLoadBlock
-(id)initWithStrUrl:(NSString*)strUrl Block:(void(^)(BOOL,HttpDownLoadBlock*))a{
if (self=[super init]) {
//保存匿名函数指针
self.httpDownLoad=a;
NSLog(@"%@",a);
if (strUrl==nil) {
return
self;
}
self.path=[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),[MyMD5 md5:strUrl]];
NSFileManager*manager=[NSFileManager defaultManager];
if ([manager fileExistsAtPath:self.path]&&![manager timeOutWithPath:[MyMD5 md5:strUrl] timeOut:60*60]) {
//有缓存时
self.data=[NSData dataWithContentsOfFile:self.path];
[self jsonValue];
}else{
//发起网络请求
[self requestDownLoad:strUrl];
}
}
return
self;
}
//开始请求
-(void)requestDownLoad:(NSString*)strUrl{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
self.myConnection=[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]] delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//接收到数据,开始接收数据
self.data=[NSMutableData dataWithCapacity:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//持续接收数据
[self.data appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//请求失败
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您的网络有问题,请检查网络"
delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",
nil];
[alertView show];
if (self.httpDownLoad) {
self.httpDownLoad(NO,self);
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
//保存数据
[self.data writeToFile:self.path atomically:YES];
[self jsonValue];
}
-(void)jsonValue{
id result=[NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
if ([result isKindOfClass:[NSArray class]]) {
self.dataArray=result;
}else{
if ([result isKindOfClass:[NSDictionary class]]) {
self.dataDic=result;
}else{
if (self.data) {
self.dataImage=[UIImage imageWithData:self.data];
}
}
}
if (self.httpDownLoad) {
NSLog(@"%@",self.httpDownLoad);
self.httpDownLoad(YES,self);
}
}
@end
// HttpDownLoadBlock.h
#import <Foundation/Foundation.h>
@interface HttpDownLoadBlock : NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
@property(nonatomic,strong)NSURLConnection * myConnection;
@property(nonatomic,strong)NSMutableData * data;
//文件生成路径
@property(nonatomic,copy)NSString * path;
//结果
@property(nonatomic,strong)NSArray * dataArray;
@property(nonatomic,strong)NSDictionary * dataDic;
@property(nonatomic,strong)UIImage * dataImage;
//需要block指针
@property(nonatomic,copy)void(^httpDownLoad)(BOOL , HttpDownLoadBlock *);
//外部调用的方法
-(id)initWithStrUrl:(NSString *)strUrl Block:(void(^)(BOOL,HttpDownLoadBlock *))a;
@end
// HttpDownLoadBlock.m
#import "HttpDownLoadBlock.h"
#import "MyMD5.h"
#import "NSFileManager+Method.h"
@implementation HttpDownLoadBlock
-(id)initWithStrUrl:(NSString*)strUrl Block:(void(^)(BOOL,HttpDownLoadBlock*))a{
if (self=[super init]) {
//保存匿名函数指针
self.httpDownLoad=a;
NSLog(@"%@",a);
if (strUrl==nil) {
return
self;
}
self.path=[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),[MyMD5 md5:strUrl]];
NSFileManager*manager=[NSFileManager defaultManager];
if ([manager fileExistsAtPath:self.path]&&![manager timeOutWithPath:[MyMD5 md5:strUrl] timeOut:60*60]) {
//有缓存时
self.data=[NSData dataWithContentsOfFile:self.path];
[self jsonValue];
}else{
//发起网络请求
[self requestDownLoad:strUrl];
}
}
return
self;
}
//开始请求
-(void)requestDownLoad:(NSString*)strUrl{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
self.myConnection=[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]] delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//接收到数据,开始接收数据
self.data=[NSMutableData dataWithCapacity:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//持续接收数据
[self.data appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//请求失败
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您的网络有问题,请检查网络"
delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",
nil];
[alertView show];
if (self.httpDownLoad) {
self.httpDownLoad(NO,self);
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
//保存数据
[self.data writeToFile:self.path atomically:YES];
[self jsonValue];
}
-(void)jsonValue{
id result=[NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
if ([result isKindOfClass:[NSArray class]]) {
self.dataArray=result;
}else{
if ([result isKindOfClass:[NSDictionary class]]) {
self.dataDic=result;
}else{
if (self.data) {
self.dataImage=[UIImage imageWithData:self.data];
}
}
}
if (self.httpDownLoad) {
NSLog(@"%@",self.httpDownLoad);
self.httpDownLoad(YES,self);
}
}
@end
相关文章推荐
- iOS小明开发笔记(十五) (Quartz2D矩阵操作)
- iOS小明开发笔记(十三) (Quartz2D简单使用二)
- iOS小明开发笔记(十二) (Quartz2D简单使用一)
- 关于xcode7 ios9的一些变化
- iOS创建系统TabBar
- iOS小明开发笔记(十一) (Quartz2D简单介绍)
- iOS去掉按钮的点击效果
- kidd风的IOS日志之学习用MetalPerformanceShaders进行图像处理(模糊效果)
- iOS 制作view渐变的效果CAGradientLayer
- 【iOS】右滑返回上一级界面手势
- iOS 判断版本是否升级,若是有新的版本,提醒升级
- iOS: 在Xcode7系列中给类名自动添加前缀
- IOS-CALayer(图层)
- iOS海哥开发笔记 (海哥原创,线程安全的几种加锁方法)
- iOS海哥开发笔记 (海哥原创,iOS 之应用性能调优的25个建议和技巧
- iOS小明开发笔记(十) (Xcode统计代码行数)
- iOS海哥开发笔记 (海哥原创,iOS 之API概述)
- iOS海哥开发笔记 (海哥原创,iOS 之Autolayout(VFL)(二))
- iOS海哥开发笔记 (海哥原创,iOS 之Autolayout(VFL)(一))
- iOS海哥开发笔记 (海哥原创,iOS 之NSBundle介绍)