iOS NSURLSession的使用

一、代码块方法

// 数据信息下载

- (void)dataload

{

    // 创建Data Task,用于打开我的csdn blog主页

    NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/image/pic/item/ac345982b2b7d0a2a3f98e71c9ef76094b369a2e.jpg"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];

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

        // 输出返回的状态码,请求成功的话为200

        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse *)response;

        NSInteger responseStatusCode = [httpResponse statusCode];

        NSLog(@"%ld", responseStatusCode);

        

        UIImage *image = [UIImage imageWithData:data];

        imageview.image = image;

    }];

    

    // 使用resume方法启动任务

    [dataTask resume];

}



二、代理方法

1、定义标识符

static NSString *const kCurrentSession      = @"Current Session";

static NSString *const kBackgroundSession   = @"Background Session";

static NSString *const kBackgroundSessionID = @"cn.edu.scnu.DownloadTask.BackgroundSession";


2、属性定义

@property (strong, nonatomic)           NSURLSession *currentSession;    // 当前会话


@property (strong, nonatomic) NSURLSessionDownloadTask *cancellableTask; // 可取消的下载任务


3、创建实例

// 创建当前的session

- (void)createCurrentSession

{

    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    self.currentSession = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:nil];

    self.currentSession.sessionDescription = kCurrentSession;

}


// 创建可取消的下载任务

- (void)cancellableDownload:(id)sender

{

    if (!self.cancellableTask)

    {

        if (!self.currentSession)

        {

            [self createCurrentSession];

        }

        

        NSString *imageURLStr = @"http://farm6.staticflickr.com/5505/9824098016_0e28a047c2_b_d.jpg";

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];

        self.cancellableTask = [self.currentSession downloadTaskWithRequest:request];

        

        [self setDownloadButtonsWithEnabled:NO];

        self.downloadedImageView.image = nil;

        

        [self.cancellableTask resume];

    }

}


4、实现代理方法

#pragma mark - NSURLSessionDownloadDelegate

// 无断点续传时的代理执行顺序:1-3-4;有断点续传时的代理执行顺序:2-1-3-4


// 执行下载任务时有数据写入

- (void)URLSession:(NSURLSession *)session

      downloadTask:(NSURLSessionDownloadTask *)downloadTask

      didWriteData:(int64_t)bytesWritten                     // 每次写入的data字节数

 totalBytesWritten:(int64_t)totalBytesWritten                // 当前一共写入的data字节数

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite // 期望收到的所有data字节数

{

    NSLog(@"1");

    

    // 计算当前下载进度

    double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;

}


// fileOffset位移处恢复下载任务

- (void)URLSession:(NSURLSession *)session

      downloadTask:(NSURLSessionDownloadTask *)downloadTask

 didResumeAtOffset:(int64_t)fileOffset

expectedTotalBytes:(int64_t)expectedTotalBytes

{

    NSLog(@"2");

}


// 完成下载任务,只有下载成功才调用该方法

- (void)URLSession:(NSURLSession *)session

      downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location

{

    NSLog(@"3");


    // 取消已经完成的下载任务

    if (downloadTask == self.cancellableTask)

    {

        self.cancellableTask = nil;

    }

}


// 完成下载任务,无论下载成功还是失败都调用该方法

- (void)URLSession:(NSURLSession *)session

              task:(NSURLSessionTask *)task

didCompleteWithError:(NSError *)error

{

    NSLog(@"4");

    if (error)

    {

        NSLog(@"下载失败:%@", error);

        [self setDownloadProgress:0.0];

        self.downloadedImageView.image = nil;

    }

}


你可能感兴趣的:(iOS NSURLSession的使用)