博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS系统异步请求封装
阅读量:2221 次
发布时间:2019-05-08

本文共 3102 字,大约阅读时间需要 10 分钟。

在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

转载地址:http://tbifb.baihongyu.com/

你可能感兴趣的文章
轻松看懂机器学习十大常用算法
查看>>
一个框架解决几乎所有机器学习问题
查看>>
特征工程怎么做
查看>>
机器学习算法应用中常用技巧-1
查看>>
机器学习算法应用中常用技巧-2
查看>>
通过一个kaggle实例学习解决机器学习问题
查看>>
决策树的python实现
查看>>
Sklearn 快速入门
查看>>
了解 Sklearn 的数据集
查看>>
用ARIMA模型做需求预测
查看>>
推荐系统
查看>>
TensorFlow-11-策略网络
查看>>
浅谈 GBDT
查看>>
如何选择优化器 optimizer
查看>>
一文了解强化学习
查看>>
CART 分类与回归树
查看>>
seq2seq 的 keras 实现
查看>>
seq2seq 入门
查看>>
什么是 Dropout
查看>>
用 LSTM 做时间序列预测的一个小例子
查看>>