2015年12月24日 星期四

Swift - 常用檔案資料夾路徑的取得方式(Home資料夾,檔案資料夾,暫存資料夾)

iOS應用程式只能在自己的資料夾下進行檔案的操作,不可以訪問其他的存儲空間,此區域被稱為沙盒(sandbox)。下面介紹常用的檔案資料夾:

1,Home資料夾 ./
整個應用程式各檔案所在的資料夾

//得到Home資料夾路徑
let homeDirectory = NSHomeDirectory()


2,Documnets資料夾 ./Documents
使用者檔案資料夾,蘋果建議將應用程式在「執行中建立」或「在執行中瀏覽到的」檔案數據儲存在該資料夾下,iTunes備份或恢復的時候會包括此資料夾

//方法1
let documentPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
    NSSearchPathDomainMask.UserDomainMask, true)
let documnetPath = documentPaths[0] as! String

//方法2
let ducumentPath2 = NSHomeDirectory() + "/Documents"


3,Library資料夾 ./Library
這個資料夾下有兩個子資料夾:Caches 和Preferences
Library/Preferences資料夾,包含應用程式的偏好設置檔案。不應該直接創建偏好設置檔案,而是應該使用NSUserDefaults類來取得和設置應用程式的偏好。
Library/Caches資料夾,主要存放暫存檔案,iTunes不會備份此資料夾,此資料夾下檔案不會再應用程式退出時刪除

//Library資料夾-方法1
let libraryPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory,
    NSSearchPathDomainMask.UserDomainMask, true)
let libraryPath = libraryPaths[0] as! String

//Library資料夾-方法2
let libraryPath2 = NSHomeDirectory() + "/Library"


//Cache資料夾-方法1
let cachePaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,
    NSSearchPathDomainMask.UserDomainMask, true)
let cachePath = cachePaths[0] as! String

//Cache資料夾-方法2
let cachePath2 = NSHomeDirectory() + "/Library/Caches"


4,tmp資料夾 ./tmp
用於存放暫存檔案,儲存應用程式再次啟動過程中不需要的資料,重啟後會清空。

//方法1
let tmpDir = NSTemporaryDirectory()

//方法2
let tmpDir2 = NSHomeDirectory() + "/tmp"


5,應用程式打包安裝的資料夾NSBundle.mainBundle()
專案打包安裝後會在NSBundle.mainBundle()路徑下,該路徑是只能讀的,不允許修改。
所以當我們專案中有一個SQLite資料庫要使用,在應用程式開啟時,我們可以把該路徑下的資料庫copy一份到Documents路徑下,以後整個專案都將使用Documents路徑下的資料庫。

//宣告一個Documents下的路徑
var dbPath = NSHomeDirectory() + "/Documents/hanggeDB.sqlite"
//判斷資料庫檔案是否存在
if !NSFileManager.defaultManager().fileExistsAtPath(dbPath){
    //取得安裝包內資料庫路徑
    var bundleDBPath:String? = NSBundle.mainBundle().pathForResource("hanggeDB", ofType: "sqlite")
    //將安裝包內資料庫copy到Documents資料夾下
    do{
        try NSFileManager.defaultManager().copyItemAtPath(bundleDBPath!, toPath: dbPath)
    }catch{}
}


參考來源

沒有留言:

張貼留言

.htaccess應用

去除WWW RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example\.com $ [ NC ] RewriteRule ^(.*) $ https: / /example.com/ $1 [ R = 301...