• iOS UI 15 网络编程2


    //

    //  RootViewController.m

    //  UI - 15网络编程

    //

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

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

    //


    #import "RootViewController.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=银行&region=大连&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];

        

        

    }


    - (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


  • 相关阅读:
    HDU 1010 Tempter of the Bone
    HDU 4421 Bit Magic(奇葩式解法)
    HDU 2614 Beat 深搜DFS
    HDU 1495 非常可乐 BFS 搜索
    Road to Cinema
    Sea Battle
    Interview with Oleg
    Spotlights
    Substring
    Dominating Patterns
  • 原文地址:https://www.cnblogs.com/yuhaojishuboke/p/5043074.html
Copyright © 2020-2023  润新知