ios 将文件保存在swift 3的文档目录中?

rqcrx0a6  于 2023-02-01  发布在  iOS
关注(0)|答案(4)|浏览(146)

我用以下代码将文件保存在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而不是字符串。
问题:

  • 如何从文件管理器中获取字符串?
  • 我的代码有可能崩溃吗?
nqwrtyyt

nqwrtyyt1#

请从另一个Angular 考虑。
URL是处理文件路径的推荐方法,因为它包含了所有附加和删除路径组件和扩展名的方便方法-而不是苹果已经删除了这些方法的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

或者,创建函数throw并将错误移交给调用方

func saveFile(with name: String) throws {
    let fileManager = FileManager.default
    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let fileURL = documentDirectory.appendingPathComponent(name)
    let image = #imageLiteral(resourceName: "Notifications")
    guard let imageData = image.jpegData(compressionQuality: 0.5) else { throw URLError(.cannotDecodeContentData) }
    try imageData.write(to: fileURL)
}
mzsu5hc0

mzsu5hc02#

按照vadian给出的上述示例,在文档目录中保存(数据)文件所需的唯一行是:
尝试图像数据.写入(到:文件URL)
获取文件路径是有趣的部分
例如:创建文件路径

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)
 }
euoag5mw

euoag5mw3#

我使用下面的方法创建“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)")
}
nwo49xxi

nwo49xxi4#

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 {
      }
   }        
}

相关问题