//git
// RootViewController.m編程
// UI - 15網絡編程json
//api
// Created by dllo on 15/11/27.緩存
// Copyright (c) 2015年 dllo. All rights reserved.網絡
//session
#import "RootViewController.h"app
#import "Network.h"異步
@interface RootViewController ()<NSURLSessionDownloadDelegate>post
@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