您的位置:首页 > 理论基础 > 计算机网络

iOS UI 17 网络请求封装

2015-12-13 16:26 691 查看
//

// RootViewController.m

// UI - 15网络编程

//

// Created by dllo on 15/11/27.

// Copyright (c) 2015年 dllo. All rights reserved.

//

#import "RootViewController.h"

#import "Network.h"

@interface
RootViewController ()<NSURLSessionDownloadDelegate>

@property (nonatomic,
retain) NSURLSessionDownloadTask *downMovieT;

@property (retain,
nonatomic) IBOutlet
UIButton *get;

@property (retain,
nonatomic) IBOutlet
UIButton *post;

@property (retain,
nonatomic) IBOutlet
UIImageView *imageview;

@property (retain,
nonatomic) IBOutlet
UIProgressView *progressv;

@property (retain,
nonatomic) IBOutlet
UIView *start;

@property (retain,
nonatomic) IBOutlet
UIButton *pause;

@property (retain,
nonatomic) IBOutlet
UIButton *button4;

@property (retain,
nonatomic) IBOutlet
UIButton *button5;

@end

@implementation RootViewController

- (void)viewDidLoad {

[super
viewDidLoad];

// Do any additional setup after loading the view from its nib.

}

- (IBAction)start:(UIButton *)sender {

//开始下载

if (NSURLSessionTaskStateSuspended ==
self.downMovieT.state) {

[self.downMovieT
resume];

}

}

- (IBAction)pause:(UIButton *)sender {

if (NSURLSessionTaskStateRunning ==
self.downMovieT.state) {

//暂停下载

[self.downMovieT
suspend];

}

// //暂停下载

// [self.downMovieT suspend];

//

}

- (IBAction)button4:(id)sender {

NSURL *url = [NSURL
URLWithString:@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg"];

NSURLSession *session = [NSURLSession
sharedSession];

NSURLSessionDownloadTask *downImage =[session
downloadTaskWithURL:url completionHandler:^(NSURL *location,
NSURLResponse *response, NSError *error) {

NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES)
lastObject];

NSLog(@"%@", cach);

//拼接文件名 -
推荐用系统推荐的文件名(与服务区文件同名),也可以自定义头文件名

//自定义文件名

// NSString *file = [cach stringByAppendingPathComponent:@"waning.png"];

//系统推荐

NSString *file = [cach
stringByAppendingPathComponent:response.suggestedFilename];

//管理文件的类

NSFileManager *fileM = [NSFileManager
defaultManager];

//将下载数据由临时文件搬到自己的缓存路径内

[fileM moveItemAtPath:location.path
toPath:file error:nil];

self.imageview.image = [UIImage
imageWithContentsOfFile:file];

}];

[downImage resume];

}

- (IBAction)button5:(id)sender {

//若已经存在任务则不再触发,直接退出返回

if (nil !=
self.downMovieT) {

return;

}

NSURL *url = [NSURL
URLWithString:@"http://hc25.aipai.com/user/656/20448656/6167672/card/25033081/card.mp4?l=a"];

NSURLRequest *request = [NSURLRequest
requestWithURL:url];

//协议代理方式请求

NSURLSession *senssion = [NSURLSession
sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration] delegate:self
delegateQueue:[NSOperationQueue
mainQueue]];

//创建下载任务

self.downMovieT = [senssion
downloadTaskWithRequest:request];

//开始任务

[_downMovieT
resume];

}

//下载器

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

{

NSLog(@"下载过程中会多次调用,
每次下载不一定多大的数据");

NSLog(@"本次下载大小:%.2fKB,
已经下载大小:%.2fKB,
总大小:%.2fKB", bytesWritten / 1024.0, totalBytesWritten / 1024.0, totalBytesExpectedToWrite / 1024.0);

self.progressv.progress = (float)totalBytesWritten / totalBytesExpectedToWrite;

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL
*)location

{

NSLog(@"下载完毕时调用");

NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES)
lastObject];

//自定义名字

NSString *file = [cach
stringByAppendingPathComponent:@"waning"];

//系统命名推荐

// NSString *file = [cach stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

NSFileManager *mrc = [NSFileManager
defaultManager];

[mrc moveItemAtPath:location.path
toPath:file error:nil];

}

- (IBAction)post:(UIButton *)sender {

NSString *urlStr =
@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

NSURL *url = [NSURL
URLWithString:urlStr];

NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];

/**************************post新增********************/

//先设置为Post模式

request.HTTPMethod =
@"POST";

NSString *bodyStr =
@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";

NSData *bodyData = [bodyStr
dataUsingEncoding:NSUTF8StringEncoding];

//再添加Body

request.HTTPBody = bodyData;

/**************************post新增********************/

NSURLSession *senssion = [NSURLSession
sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration] ];

NSURLSessionDataTask * PostT = [senssion
dataTaskWithRequest:request completionHandler:^(NSData *data,
NSURLResponse *response, NSError *error) {

id result = [NSJSONSerialization
JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:nil];

NSLog(@"%@", result);

}];

[PostT resume];

}

- (IBAction)get:(UIButton *)sender {

// //5, 网址字符串

// NSString *urlstr = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";

// //6, IOS9.0后使用的未明字符转换,未明字符如中文

// NSString *urlEncode = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

// //4,创建url

// NSURL *url = [NSURL URLWithString:urlEncode];

//

// //3,创建请求对象,request可设置信息如:url,方式(GET/POST),超时时间等

//// NSURLRequest *request = [NSURLRequest requestWithURL:url];

// NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:60 ];

// //1,创建NSURLSession对象,选择默认配置

// NSURLSession *sessioin = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//

// //2 ,创建请求任务,当异步请求完成会调用block,在block里面完成数据处理

//

// NSURLSessionDataTask * getTast = [sessioin dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

//

// //当数据请求完毕,在此处解析数据

// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

// NSLog(@"%@",dic);

// /**

// * 注意刷新界面 [self.tablev releaload]

// */

//

// }];

// //7, 开始任务

// [getTast resume];

//方法1

// void (^netDataBlock)(NSData *) = ^(NSData *netdata) {

// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:netdata options:NSJSONReadingMutableContainers error:nil];

// NSLog(@"%@",dic);

// };

//

// [Network getDataSyWithURLStr:@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295"
block:netDataBlock ];

//方法2

[Network
getDataSyWithURLStr:@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295"
block:^(NSData *netdata) {

NSDictionary *dic = [NSJSONSerialization
JSONObjectWithData:netdata options:NSJSONReadingMutableContainers
error:nil];

NSLog(@"%@",dic);

}];

}

- (void)didReceiveMemoryWarning {

[super
didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

/*

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/

- (void)dealloc {

[_get release];

[_post
release];

[_downMovieT
release];

[_button4
release];

[_imageview
release];

[_button5
release];

[_progressv
release];

[_start
release];

[_pause
release];

[super dealloc];

}

@end

//

// Network.h

// UI - 15网络编程

//

// Created by dllo on 15/11/30.

// Copyright (c) 2015年 dllo. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface Network :
NSObject

+ (void)getDataSyWithURLStr:(NSString *)urlstr block:(void (^)(NSData *))block;

@end

//

// Network.m

// UI - 15网络编程

//

// Created by dllo on 15/11/30.

// Copyright (c) 2015年 dllo. All rights reserved.

//

#import "Network.h"

@implementation Network

+ (void)getDataSyWithURLStr:(NSString *)urlstr block:(void (^)(NSData *))block

{

//6, IOS9.0后使用的未明字符转换,未明字符如中文

NSString *urlEncode = [urlstr
stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
URLQueryAllowedCharacterSet]];

//4,创建url

NSURL *url = [NSURL
URLWithString:urlEncode];

//3,创建请求对象,request可设置信息如:url,方式(GET/POST),超时时间等

// NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLRequest *request = [NSURLRequest
requestWithURL:url cachePolicy:
NSURLRequestUseProtocolCachePolicy timeoutInterval:60 ];

//1,创建NSURLSession对象,选择默认配置

NSURLSession *sessioin = [NSURLSession
sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]];

//2 ,创建请求任务,当异步请求完成会调用block,在block里面完成数据处理

NSURLSessionDataTask * getTast = [sessioin
dataTaskWithRequest:request completionHandler:^(NSData *data,
NSURLResponse *response, NSError *error) {

block(data);

//当数据请求完毕,在此处解析数据

// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

// NSLog(@"%@",dic);

/**

* 注意刷新界面 [self.tablev releaload]

*/

}];

//7,
开始任务

[getTast resume];

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: