iOS之网上下载数据的两种方式

//

//  ViewController.m

//  文件下载

//

//  Created by zj on 16/5/17.

//  Copyright © 2016 zj. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()<NSURLSessionDownloadDelegate>


@end


@implementation ViewController

使用前记得在info.plist里面导入网络协议

在此我使用的url是我本地的服务器  大家可以使用网上的接口下载尝试

/*

 使用block方式下载数据 适合下载小文件 不能监听下载过程

- (void)viewDidLoad {

    [super viewDidLoad];

  NSString *str = @"http://127.0.0.1/设计模式解析.pdf";

    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];

    创建下载会话任务

    NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        拼接文件路径,用来存放我们下载好的文件

        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:response.suggestedFilename];

        将返回的location转化成路径格式

        NSString *temPath = [location path];

        准备二进制数据

        NSData *data = [NSData dataWithContentsOfFile:temPath];

        创建文件处理对象

        NSFileManager *fileManage = [NSFileManager defaultManager];

        把下载好的文件写入到我们准备好的地址里去

        [fileManage createFileAtPath:path contents:data attributes:nil];

        

    }];

     开始下载任务

    [downLoadTask resume];

}

*/


-(void)viewDidLoad{

    [super viewDidLoad];

    //使用代理方式来下载文件  一般用来下载大一点的文件 可以监听下载过程

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/Office4mac.dmg"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]] ;

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];

    [downloadTask resume];

}

//监听下载的代理方法 

//下载完成时调用

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location{

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"user.mmm"];

        NSString *temPath = [location path];

           NSData *data = [NSData dataWithContentsOfFile:temPath];

            NSFileManager *fileManage = [NSFileManager defaultManager];

            [fileManage createFileAtPath:path contents:data attributes:nil];

    

}

//下载过程调用

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

      didWriteData:(int64_t)bytesWritten

 totalBytesWritten:(int64_t)totalBytesWritten

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

      NSLog(@"这次共下载=%lld 当前下载总数= %lld  期待下载的总数%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值