MKNetworkOperation类不仅可以指定下载文件的位置,还可以获得下载的进度,由于它采用整个应用共享单一队列的设计,所以可以准确地计算下载进度。话不多说,下面通过一个例子来说明下载数据和上传数据。
MKNetworkKit框架的下载地址:框架下载地址
下载数据
项目的配置如图所示:
首先新建一个SimpleViewApplication的项目,添加MKNetworkKit库文件到项目中最好使用如下的方式添加到项目中,如图所示:
这样直接可以引用文件就可以了,不然需要添加文件夹的路径才可以引用库。
其次添加一个.pch的配置文件,需要注意的是添加之后需要在如图所示的位置将文件的路径加到项目中。
将如图所示的文件加入项目中方式同MKNetworkKit库
库下载地址见库文件地址
#import "NSNumber+Message.h"
#import "NSString+URLEncoding.h"
还需要将以下几个Framework添加到项目中如图所示:
添加方式如图所示:
还有一点需要提到的是:
Google后查证,iOS9引入了新特性App Transport Security (ATS)。详情:App Transport Security (ATS)
新特性要求App内访问的网络必须使用HTTPS协议。
但是现在公司的项目使用的是HTTP协议,使用私有加密方式保证数据安全。现在也不能马上改成HTTPS协议传输。
所以需要做的是:
所有关于项目的说明都已经结束下面是功能说明了。
Main.storyboard很简单如图所示,这里就不一一说明了。
ViewController实现代码
#import "ViewController.h"
#import "MKNetworkKit.h"
#import "NSNumber+Message.h"
#import "NSString+URLEncoding.h"
@interface ViewController ()
- (IBAction)onClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onClick:(id)sender {
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory=paths[0];
NSString *downloadPath=[cachesDirectory stringByAppendingPathComponent:@"test1.jpg"];
NSString *path=[[NSString alloc]initWithFormat:@"/service/download.php?email=%@&FileName=test1.jpg",@"784087156@qq.com" ];
path=[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
MKNetworkEngine *engine=[[MKNetworkEngine alloc]initWithHostName:@"51work6.com" customHeaderFields:nil];
MKNetworkOperation *downloadOption=[engine operationWithPath:path params:nil httpMethod:@"POST"];
[downloadOption addDownloadStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]];
[downloadOption onDownloadProgressChanged:^(double progress) {
NSLog(@"download progress:%.2f%%",progress*100.0);
self.progressView.progress=progress;
}];
[downloadOption addCompletionHandler:^(MKNetworkOperation *operation) {
NSLog(@"download file finished!");
NSData *data=[operation responseData];
if(data)
{
NSError *error;
NSDictionary *resDict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if(!resDict)
{
NSNumber *resultCodeObj=[resDict objectForKey:@"ResultCode"];
NSString *errorStr=[resultCodeObj errorMessage];
UIAlertView *alerView=[[UIAlertView alloc]initWithTitle:@"错误信息" message:errorStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alerView show];
}
}else
{
UIImage *img=[UIImage imageWithContentsOfFile:downloadPath];
self.imageView1.image=img;
}
} errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
NSLog(@"MKNetwork请求错误:%@",[error localizedDescription]);
}];
[engine enqueueOperation:downloadOption];
}
沙箱目录的获得在我的之前的博客有详细介绍,这里只贴关键代码。
上传数据
界面和下载数据是一样的。项目的配置情况如下:
添加了两个测试图片用于上传的。
功能代码如下:
ViewController实现
#import "ViewController.h"
#import "MKNetworkKit.h"
#import "NSString+URLEncoding.h"
#import "NSNumber+Message.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
- (IBAction)onClick:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onClick:(id)sender {
NSString *filePath=[[NSBundle mainBundle]pathForResource:@"test1" ofType:@"jpg"];
NSString *path=[[NSString alloc]initWithFormat:@"/service/upload.php"];
NSMutableDictionary *param=[[NSMutableDictionary alloc]init];
[param setValue:@"784087156@qq.com" forKey:@"email"];
MKNetworkEngine *engine=[[MKNetworkEngine alloc]initWithHostName:@"51work6.com" customHeaderFields:nil];
MKNetworkOperation *op=[engine operationWithPath:path params:param httpMethod:@"POST"];
[op addFile:filePath forKey:@"file"];
[op setFreezable:YES];
[op addCompletionHandler:^(MKNetworkOperation *operation) {
NSLog(@"upload file finished!");
NSData *data=[operation responseData];
if(data)
{
NSError *eror;
NSDictionary *resDict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&eror];
if(resDict)
{
NSNumber *resultCodeObj=[resDict objectForKey:@"ResultCode"];
NSString *errorStr=[resultCodeObj errorMessage];
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"错误信息" message:errorStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
return ;
}
}
[self seeImage];
} errorHandler:^(MKNetworkOperation *errorOp, NSError *error) {
NSLog(@"MKNetwork请求错误:%@",[error localizedDescription]);
}];
[engine enqueueOperation:op];
}
-(void)seeImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = paths[0];
NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:@"1.jpg"];
NSString *path = [[NSString alloc] initWithFormat:@"/service/download.php?email=%@&FileName=1.jpg",@"784087156@qq.com"];
MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil];
[engine emptyCache];
MKNetworkOperation *downloadOperation = [engine operationWithPath:path params:nil httpMethod:@"POST" ssl:NO];
[downloadOperation addDownloadStream:[NSOutputStream outputStreamToFileAtPath:downloadPath
append:YES]];
[downloadOperation onDownloadProgressChanged:^(double progress) {
NSLog(@"download progress: %.2f", progress*100.0);
_progressView.progress = progress;
}];
[downloadOperation addCompletionHandler:^(MKNetworkOperation *operation) {
NSLog(@"download file finished!");
NSData *data = [operation responseData];
if (data) {
NSError *eror;
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&eror];
if (!resDict) {
NSNumber *resultCodeObj = [resDict objectForKey:@"ResultCode"];
NSString *errorStr = [resultCodeObj errorMessage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
} else {
UIImage *img = [UIImage imageWithContentsOfFile:downloadPath];
_imageView1.image = img;
}
} errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]);
}];
[engine enqueueOperation:downloadOperation];
}
至此所有的代码部分都已经放在上面了,点击Go按钮ImageView会显示上传的照片并显示下载进度。上传主要是将图片上传到51work6.com网站上,因为我之前已经注册了邮箱,所以直接可以访问它提供的WebService读写数据。希望对大家有帮助!有什么问题可以在下面提问。