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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44646186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:15:28  来源:igfitidea点击:

Save file in document directory in swift 3?

iosswiftnsfilemanagernsdocumentdirectory

提问by TechChain

I am saving files in a document directory in swift 3 with this code:

我正在使用以下代码将文件保存在 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

But as you can see, I am not using filemanagerto get document directory path as filemanagergives only URL not string.

但是正如您所看到的,我没有使用filemanager获取文档目录路径,因为filemanager只给出了 URL 而不是字符串。

Questions:

问题:

  • How to get string from file manager?
  • Is there any chance of crash in my code?
  • 如何从文件管理器获取字符串?
  • 我的代码有没有崩溃的可能?

回答by vadian

Please think the other way round.

请换个角度思考。

URLis the recommended way to handle file paths because it contains all convenience methods for appending and deleting path components and extensions – rather than Stringwhich Apple has removed those methods from.

URL是处理文件路径的推荐方法,因为它包含所有用于添加和删除路径组件和扩展的便捷方法——而不是StringApple 从中删除了这些方法。

You are discouraged from concatenating paths like path = path + name. It's error-prone because you are responsible for all slash path separators.

不鼓励您连接像path = path + name. 这很容易出错,因为您负责所有斜杠路径分隔符。

Further you don't need to create a file with FileManager. Datahas a method to write data to disk.

此外,您不需要使用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 = UIImageJPEGRepresentation(image, 0.5) {
        try imageData.write(to: fileURL)
        return true
    }
} catch {
    print(error)
}
return false

回答by subCipher

following the above example given by vadian the only line you need to save a (Data)file in Document Directory is:

按照vadian给出的上述示例,您需要在文档目录中保存(数据)文件的唯一行是:

try imageData.write(to: fileURL)

尝试 imageData.write(to: fileURL)

Getting the file path is the interesting part

获取文件路径是有趣的部分

ex: create the file path

例如:创建文件路径

 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
}

call the function:

调用函数:

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

回答by Mahyar

I use the following method for creating "Test.txt" file. Hope it helps you.

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

回答by Neeraj IOS

func copyandpast() {

功能复制和过去(){

    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{

        }



    }


}