NSURLSession的应用
iOS7以后發(fā)布了NSURLSession用來替換NSURLConnection,NSURLSession使用方式有以下兩種:
1.block方式
(1)創(chuàng)建的步驟
獲取單例會話對象
創(chuàng)建URL對象
隱含創(chuàng)建request
創(chuàng)建NSURLSessionDataTask
(2)使用NSURLSessionDataTask
創(chuàng)建session
創(chuàng)建URL
創(chuàng)建URLRequest
創(chuàng)建NSURLSessionDataTask
(3)使用NSURLSessionDownloadTask
// 1.得到session對象
NSURLSession *session = [NSURLSession sharedSession];
// 2.創(chuàng)建URL對象
2.代理方式
(void)downLoadTask2 {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
// 使用配置對象獲取會話對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];// 創(chuàng)建一個URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/test.mp4“];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];[task resume];
}
- (void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager moveItemAtPath:location.path toPath:filePath error:nil];
}
- (void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@”已經(jīng)下載了:%f”, progress);
}
總結(jié)
以上是生活随笔為你收集整理的NSURLSession的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SEP图示
- 下一篇: Cacti v1.2.8(CVE-202