NSArrayURL , userDefault filePath and URL

杀马特。学长 韩版系。学妹 提交于 2019-12-02 17:17:24

问题


I have one pdf source code and I want to add the Url in Array and use UserDefault

let defaults = UserDefaults.standard

struct Constants {

    static let myKeyURL = "myKeyUrl"

}

I download the Pdf Like This

let documentsPath =NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

let fileName = urlString as NSString;
let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

After I save the Path like This

var arrayUrl = [String]()
arrayUrl.append(filePath)
self.defaults.set(arrayUrl, forKey: Constants.myKeyURL)

Now I want to Read

var arrayUrl = [String]()
defaults.stringArray(forKey: Constants.myKeyURL)
arrayUrl = defaults.stringArray(forKey: Constants.myKeyURL)!

I need to Read in This Model

documents = arrayUrl.flatMap { PDFDocument(url: $0 ) }

But I received Cannot convert value of type 'String' to expected argument type 'URL' I need this URL (arrayUrl) File in this format file:///private/var/mobile/Containers/Data/Application/----/Documents/Sample.pdf


回答1:


The error is clear:

PDFDocument(url: expects URL, you pass String which is a classic type mismatch.

You have to create URL instances from the strings

documents = arrayUrl.flatMap { PDFDocument(url: URL(fileURLWithPath: $0) ) }

However you are discouraged from saving the full path because the path to the Documents folder changes. Save only the file name or relative path and get the actual path to the Documents folder on each application launch.



来源:https://stackoverflow.com/questions/48551064/nsarrayurl-userdefault-filepath-and-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!