NSArrayURL,userDefault filePath和URL [英] NSArrayURL , userDefault filePath and URL

查看:64
本文介绍了NSArrayURL,userDefault filePath和URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pdf源代码,我想在数组中添加Url并使用UserDefault

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"

}

我这样下载Pdf

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

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

像这样保存路径之后

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

现在我想阅读

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

我需要阅读此模型

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

但是我收到了 无法将字符串"类型的值转换为预期的参数类型"URL" 我需要此URL( arrayUrl )文件,其格式为 file:///private/var/mobile/Containers/Data/Application/----/Documents/Sample.pdf

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

推荐答案

错误很明显:

PDFDocument(url:期望URL,您传递了String,这是经典类型不匹配.

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

您必须从字符串创建URL实例

You have to create URL instances from the strings

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

但是,不建议您保存完整路径,因为Documents文件夹的路径已更改.在每次启动应用程序时,仅保存文件名或相对路径,并获取到Documents文件夹的实际路径.

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.

这篇关于NSArrayURL,userDefault filePath和URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆