您的位置:首页 > 其它

NSURLSession使用模板和AFNetworking使用模板(REST风格)

2016-12-17 13:18 218 查看

1.NSURLSession使用模板

NSURLSession是苹果ios7后提供的api,用来替换 NSURLConnection
会话指的是程序和服务器的通信对象
//一.简单会话不可以配合会话(get请求)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
//1.将字符串转化成URL字符串
strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

//2.用单列创建简单会话
NSURLSession *session = [NSURLSession sharedSession];
//3.会话任务(会话都是基于会话任务的)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//页面交互放在主线程进行
dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];

//4.新建任务默认是暂停的 要自己执行
[task resume];
}

//二.默认会话,可以对会话进行配置(GET)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];

strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

//1.创建默认会话配置对象
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//2.1创建默认会话 (主线程中执行)
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//2.2不需要再次设置在主线程中执行
//dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
//});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];

//3.执行会话任务
[task resume];
}

//三.默认会话 (POST)[和get的主要区别是NSMutableURLRequest]

- (void)startRequest
{
NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php";
NSURL *url = [NSURL URLWithString:strURL];

//1.构建NSMutableURLRequest对象
NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

//2.构建默认会话
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

//3.构建会话任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
//});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];

//4.执行会话任务
[task resume];
}

四.下载文件或图片,用的是下载会话任务(一般get post用的都是数据任务NSURLSessionDataTask)支持后台下载

//四.下载图片或文件,用会话下载任务NSURLSessionDownloadTask(支持后台下载)
- (IBAction)onClick:(id)sender
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/download.php?email=%@&FileName=test1.jpg", @"414875346@qq.com"];
NSURL *url = [NSURL URLWithString:strURL];

//1.构造默认会话 (基于委托代理非block回调模式)
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];//1.1主线程执行

//2.创建会话下载任务
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
//3.执行任务
[downloadTask resume];
}

//4.实现回调接口,显示进度条
#pragma mark -- 实现NSURLSessionDownloadDelegate委托协议
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
//1.2 不用再次单独设置在主进程里进行
[_progressView setProgress:progress animated:TRUE];
NSLog(@"完成进度= %.2f%%", progress * 100);
NSLog(@"当前接收: %lld 字节 (累计已下载: %lld 字节)  期待: %lld 字节.", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
//5.下载完成时回调
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
//6.将临时文件保存到沙盒中
NSLog(@"临时文件: %@\\n", location);

//6.1构建保存到沙盒的文件的路径
NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];
NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:@"test1.jpg"];
NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath];

//6.2如果已经存在先删除
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if ([fileManager fileExistsAtPath:downloadStrPath]) {
[fileManager removeItemAtPath:downloadStrPath error:&error];
if (error) {
NSLog(@"删除文件失败: %@", error.localizedDescription);
}
}

//6.3将文件保存到沙盒中
error = nil;
if ([fileManager moveItemAtURL:location toURL:downloadURLPath error:&error]) {
NSLog(@"文件保存成功: %@", downloadStrPath);
UIImage *img = [UIImage imageWithContentsOfFile:downloadStrPath];
self.imageView1.image = img;
} else {
NSLog(@"保存文件失败: %@", error.localizedDescription);
}
}

2.AFNetwork使用模板(AFNetwork3 底层也是NSURLSession) <swift推荐用Alamofire>

//一.get请求(AFNetworking)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];

strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

//1.默认配置
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//2.构建AF会话AFURLSessionManager  (其实就是将NSURLSession对象换掉,其他函数接口都一样)
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//3.构建AF生产的会话任务
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//3.1注意responseObject可以是字典或数组,不需要我们自己解析

NSLog(@"请求完成...");
if (!error) {
[self reloadView:responseObject];
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
//4.执行任务
[task resume];
}

//二.post请求(AFNetworking)

- (void)startRequest
{
NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php";
NSURL *url = [NSURL URLWithString:strURL];

//1.设置参数构建NSMutableURLRequest
NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

//2.就NSMutableURLRequest对象不一样,其他都和get一样
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//3.
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
[self reloadView:responseObject];
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
//4.
[task resume];
}

//三.下载文件或图片(AFNetworking)<不用委托代理的模式,直接在block里处理>(既不是POST也不是GET)

- (IBAction)onClick:(id)sender
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/download.php?email=%@&FileName=test1.jpg", @"414875346@qq.com"];

NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

//1.构建会话AFURLSessionManager
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//2.构建AF创建的会话下载任务
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
//3.设置进度条(需要设置在主线程进行)
NSLog(@"本地化信息=%@", [downloadProgress localizedDescription]);//完成百分比
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setProgress:downloadProgress.fractionCompleted animated:TRUE];
});

} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//4.指定文件下载好后的保存路径即可。不用自己操作(带返回参数的block)
NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];
NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:[response suggestedFilename]];//4.1服务器端存储的文件名
NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath];

return downloadURLPath;

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//5.服务器返回数据后调用
NSLog(@"File downloaded to: %@", filePath);
NSData *imgData = [[NSData alloc] initWithContentsOfURL:filePath];
UIImage *img = [UIImage imageWithData:imgData];
self.imageView1.image = img;

}];
//6.执行会话下载任务
[downloadTask resume];
}

//四.上传文件或图片(AFNetworking)(也用POST)

- (IBAction)onClick:(id)sender
{
_label.text = @"上传进度";
_progressView.progress = 0.0;

NSString *uploadStrURL = @"http://www.51work6.com/service/upload.php";
NSDictionary *params = @{@"email" : @"414875346@qq.com"};

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test2" ofType:@"jpg"];

//1.构建NSMutableURLRequest(带上传文件对象)
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
URLString:uploadStrURL parameters:params
constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"file" fileName:@"1.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
//2.创建会话
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//3.创建会话上传任务(用AF构建)
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request
progress:^(NSProgress *uploadProgress) {
//3.1 上传进度条(主进程中显示)
NSLog(@"上传: %@", [uploadProgress localizedDescription]);
dispatch_async(dispatch_get_main_queue(), ^{
[_progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//3.2 上传完后操作
if (!error) {
NSLog(@"上传成功");
[self download];
} else {
NSLog(@"上传失败: %@", error.localizedDescription);
}
}];
//4.执行任务
[uploadTask resume];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: