版本:7.2
语言:Swift2
A、沙盒所在目录:
print("沙盒所在目录:\(NSHomeDirectory())");B、沙盒安装目录
print("沙盒安装目录: \(NSBundle.mainBundle().bundlePath)");观察运行结果。
沙盒所在目录:/Users/XXX/Library/Developer/CoreSimulator/Devices/3CA1FFF2-F868-4D3C-AA01-E4BEEEFBAC36/data/Containers/Data/Application/CAB24E30-8289-42B1-BD99-CC2E994E4540 沙盒安装目录: /Users/XXX/Library/Developer/CoreSimulator/Devices/3CA1FFF2-F868-4D3C-AA01-E4BEEEFBAC36/data/Containers/Bundle/Application/D58FD8F3-8223-4542-BEC6-CCA535D06011/沙盒.app激活Finder,进入上面输出的路径中,会看到下图所示的目录结构图:
Documents: 用户自己生产的数据保存在该目录下,iTunes备份和恢复的时候,会包括此目录。
Library:存储程序的默认设置,其他状态信息。
tmp:提供创建临时文件。
A、查询多沙盒的路径,源码如下:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /// 查询 querySandBoxOperation(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /// 自己添加的函数 func querySandBoxOperation() { /// 获取home路径 let homePath = NSHomeDirectory(); print("沙盒的Home路径是:\(homePath)\n"); /// 输出document路径 let documentPath:Array = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>; print("沙盒的document路径为:\(documentPath[0])\n"); /// 输出library路径 let libPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true); print("沙盒的library路径为:\(libPath[0])\n"); /// 输出tmp路径 let tmpPath = NSTemporaryDirectory(); print("沙盒的tmp路径为:\(tmpPath)\n"); /// 输出沙盒的缓存目录 let cachePath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true); print("沙盒的缓存目录为:\(cachePath[0])"); } }
B、读写文
document目录下,尝试读写文件,源码:
/// 写操作 func writeFileOperation() { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>; let documentPath:String? = path[0]; if nil != documentPath { /// 文件路径 let filePath = documentPath! + "ios.txt"; /// 文件内容 let fileContents:NSArray = ["hello", "swift"]; let result = fileContents.writeToFile(filePath, atomically: true); result == true ? print("写入成功"):print("写入失败"); } else { print("目录不存在"); } } /// 读操作 func readFileOperatiob() { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>; let documentPath:String? = path[0]; let readPath = documentPath! + "ios.txt"; let fileContent = NSArray(contentsOfFile: readPath); print("文件内容如下:\n\(fileContent!)"); }接着,调用写入和读写方法
override func viewDidLoad() { super.viewDidLoad() /// 查询 /// querySandBoxOperation(); writeFileOperation(); readFileOperatiob(); }运行结果如下: