[英]Save file in document directory in swift 3?
我正在使用以下代碼將文件保存在 swift 3 的文檔目錄中:
fileManager = FileManager.default
// let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
path = path + name
let image = #imageLiteral(resourceName: "Notifications")
let imageData = UIImageJPEGRepresentation(image, 0.5)
let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil)
print("bool is \(bool)")
return true
但是正如您所看到的,我沒有使用filemanager
來獲取文檔目錄路徑,因為filemanager
只提供 URL 而不是字符串。
問題:
請換個角度思考。
URL
是處理文件路徑的推薦方式,因為它包含用於添加和刪除路徑組件和擴展的所有便捷方法——而不是 Apple 從中刪除這些方法的String
。
不鼓勵您連接路徑,例如path = path + name
。 這很容易出錯,因為您負責所有斜杠路徑分隔符。
此外,您不需要使用FileManager
創建文件。 Data
有一種將數據寫入磁盤的方法。
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent(name)
let image = #imageLiteral(resourceName: "Notifications")
if let imageData = image.jpegData(compressionQuality: 0.5) {
try imageData.write(to: fileURL)
return true
}
} catch {
print(error)
}
return false
按照vadian給出的上述示例,您需要在文檔目錄中保存(數據)文件的唯一行是:
嘗試 imageData.write(to: fileURL)
獲取文件路徑是有趣的部分
例如:創建文件路徑
func createNewDirPath( )->URL{
let dirPathNoScheme = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
//add directory path file Scheme; some operations fail w/out it
let dirPath = "file://\(dirPathNoScheme)"
//name your file, make sure you get the ext right .mp3/.wav/.m4a/.mov/.whatever
let fileName = "thisIsYourFileName.mov"
let pathArray = [dirPath, fileName]
let path = URL(string: pathArray.joined(separator: "/"))
//use a guard since the result is an optional
guard let filePath = path else {
//if it fails do this stuff:
return URL(string: "choose how to handle error here")!
}
//if it works return the filePath
return filePath
}
調用函數:
let shinnyNewURLpath = createNewDirPath( )
//write data to file using one line in do/catch operation
do {
try yourDataObject?.write(to: shinnyNewURLpath)
}
catch {
print("catch error",error.localizedDescription)
}
我使用以下方法創建“Test.txt”文件。 希望對你有幫助。
func createFile() {
let fileName = "Test"
let documentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("File PAth: \(fileURL.path)")
}
func copyandpaste() {
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let dbpath: NSString = path[0] as NSString
let strdbpath = dbpath.strings(byAppendingPaths: ["mydb.db"])[0]
print(strdbpath)
let fmnager = FileManager.default
if !fmnager.fileExists(atPath: strdbpath) {
let local = Bundle.main.path(forResource: "mydb", ofType: "db")
do {
try fmnager.copyItem(atPath: local!, toPath: strdbpath)
} catch {
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.