Swift 从零开始 11_多文件下载及存到沙盒

本文主要说说,App第一次启动时,去下载一些数据保存到沙盒该如何实现.
这里用的是ios7后新出的NSUrlSession
先看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
func downloadGameAudioWithUrl(urlStr: String) {
// 1. URL
let url = NSURL(string: urlStr)
let request = NSURLRequest(URL: url!)
// 2. 自定义session,需要设置代理
// 选择默认配置信息
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let downloadSession = NSURLSession(configuration:
config, delegate: self, delegateQueue: nil)
// 3. 发起下载任务(在这里回调里面,就可以对下载好的文件进行处理)
let downloadTask = downloadSession.downloadTaskWithRequest(request) { (location, response, error) in
// 下载的位置,沙盒中tmp目录中的临时文件,会被及时删除
print("文件下载路径: \(location.path)")
/*
document 备份,下载的文件不能放在此文件夹中
cache 缓存的,不备份,重新启动不会被清空,如果缓存内容过多,可以考虑新建一条线程检查缓存目录中的文件大小,自动清理缓存,给用户节省控件
tmp 临时,不备份,不缓存,重新启动iPhone,会自动清空
*/
//要把下载下来的文件,从tmp文件夹拷贝到cache文件夹下
//获取cachew文件路径
let path = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).lastEle
//获取下载文件的名字保存以便下面的路径拼接
self.downloadFileName = (url?.lastPathComponent)!
// 拼接文件路径
let filePath = path.stringByAppendingString("/" + self.downloadFileName)
print("文件保存路径: \(filePath)")
//创建文件管理器
//这里,copyItemAtPath方法需要做异常处理
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.copyItemAtPath(location!.path!, toPath: filePath)
} catch let error as NSError {
// 发生了错误
print(error.localizedDescription)
}
}
// 4. 启动下载任务
downloadTask.resume()
}
}
后记:
这里只提到了我项目中用到的方法,很有很多方法很多思路可以实现,欢迎大家来讨论!