gpt4 book ai didi

swift2 - swift 。无法将文件保存到 DocumentDirectory。怎么了?

转载 作者:行者123 更新时间:2023-12-04 02:14:59 25 4
gpt4 key购买 nike

这是我的代码:

let fileName = "someFileName"

func saveDataToFile(urlStr:String){
let url = NSURL(string: urlStr)
var data:NSData!
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName

let fileManager = NSFileManager.defaultManager()

data = NSData(contentsOfURL: url!)
print(data) // prints a lot of data
if data != nil{
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
}

}

现在我想读取这个数据:

func readDataFromFile(){
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath) // prints the same path
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath){
data = fileManager.contentsAtPath(filePath)
}else{
print("*****BAD*****") // always prints this which means that file wasn`t created
}
}

第一个函数有什么问题?将文件保存到 DocumentDirectory 的正确方法是什么?

最佳答案

好的,在这种情况下,答案如下:

首先需要创建目录(又名文件夹),然后才在该目录中创建文件。

添加到代码中:

let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)

do{
try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
print(error.localizedDescription)
}

正如我在这之后所说的那样,你创建了你的文件:

fileManager.createFileAtPath(文件路径,内容:数据,属性:nil)

感谢Eric.D

希望有人会觉得这很有用。

关于swift2 - swift 。无法将文件保存到 DocumentDirectory。怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com