NSArrayURL , userDefault filePath and URL

2019-03-05 17:21发布

问题:

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.