目錄:[Swift]Xcode實際操做html
本文將演示如何獲取程序沙箱結構中,常見的幾個目錄。swift
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】緩存
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view, typically from a nib. 8 9 //得到應用程序的路徑, 10 //包含三個文件夾:1.文檔目錄 2.庫目錄 3.臨時目錄 4.以及一個程序包 11 //該目錄就是應用程序的沙盒,程序只能訪問該目錄下的內容。 12 let homePath = NSHomeDirectory() 13 //在控制檯打印輸出程序包主目錄的路徑 14 print("homePath:\(homePath)") 15 16 //系統會爲每一個程序,生成一個私有目錄,並隨機生成一個數字字母串做爲目錄名。 17 //在每次程序啓動時,這個目錄名稱都是不一樣的。 18 //而使用此方法,則能夠i得到對應的目錄集合。 19 let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, 20 FileManager.SearchPathDomainMask.userDomainMask, 21 true) 22 //得到並輸出目錄集合中的第一個元素,即沙箱中的文檔目錄。 23 //應該將應用程序的全部數據文件,寫入到這個目錄下。 24 //這個目錄一般用於存儲用戶數據。 25 print("documentPath1:\(documentPaths[0])") 26 //建立一個字符串對象,該字符串對象一樣表示沙箱中的文檔目錄 27 let documentPath2 = NSHomeDirectory() + "/Documents" 28 //在控制檯打印輸出該目錄,並與上一條日誌比較是否相同 29 print("documentPath2:\(documentPath2)") 30 31 //使用相同的方式,得到沙箱下的庫目錄。 32 //這個目錄下,包含兩個子目錄:1.緩存目錄 2.參數目錄 33 let libraryPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, 34 FileManager.SearchPathDomainMask.userDomainMask, 35 true) 36 //在控制檯打印輸出庫目錄 37 print("libraryPath1:\(libraryPaths[0])") 38 //建立一個字符串對象,該字符串對象一樣表示沙箱中的庫目錄 39 let libraryPath2 = NSHomeDirectory() + "/Library" 40 //在控制檯打印輸出該目錄,並與上一條日誌比較是否相同 41 print("libraryPath2:\(libraryPath2)") 42 43 //使用相同的方式,得到沙箱下的緩存目錄。 44 let cachePaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, 45 FileManager.SearchPathDomainMask.userDomainMask, 46 true) 47 //得到並在控制檯打印輸出緩存目錄, 48 //該目錄用於存放應用程序專用的支持文件, 49 //保存應用程序再次啓動過程當中,須要的信息 50 print("cachePath1:\(cachePaths[0])") 51 //建立一個字符串對象,該字符串對象一樣表示沙箱中的緩存目錄, 52 let cachePath2 = NSHomeDirectory() + "/Library/Caches" 53 //在控制檯打印輸出該目錄,並與上一條日誌比較是否相同 54 print("cachePath2:\(cachePath2)") 55 56 //建立一個字符串對象,該字符串對象一樣表示沙箱中的臨時目錄 57 let tmpPath1 = NSTemporaryDirectory() 58 //在控制檯打印輸出沙箱目錄的臨時文件夾 59 print(tmpPath1) 60 61 //從沙箱的根目錄,也能夠定位到臨時文件夾 62 let tmpPath2 = NSHomeDirectory() + "/tmp" 63 //在控制檯打印輸出沙箱目錄的臨時文件夾 64 //和上面輸出的臨時文件夾的日誌進行比較 65 print(tmpPath2) 66 } 67 68 override func didReceiveMemoryWarning() { 69 super.didReceiveMemoryWarning() 70 // Dispose of any resources that can be recreated. 71 } 72 }