swift3 – 解决对appendingPathComponent错误的模糊使用

前端之家收集整理的这篇文章主要介绍了swift3 – 解决对appendingPathComponent错误的模糊使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码在我使用 swift 2.2发布和更新的应用程序中运行良好.我只是迁移到swift 3,现在我得到以下编译时错误; “使用appendingPathComponent”与行的模糊使用:

let PDFPathFileName = documentDirectory.appendingPathComponent(fileName as String)

在这:

func returnPDFPath() -> String {
      let path:NSArray =         NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true) as NSArray
      let documentDirectory: AnyObject = path.object(at: 0) as AnyObject
      let PDFPathFileName = documentDirectory.appendingPathComponent(fileName as String)

      return PDFPathFileName
 }

 @IBAction func reveiwPDFSendCliked(_ sender: AnyObject) {

    let pdfPathWithFileName = returnPDFPath()

    generatePDFs(pdfPathWithFileName)
 }

代码负责将文件路径返回到documentDirectory,该文件路径将在用户单击查看并保存PDF按钮时用于保存PDF文件.任何建议将不胜感激.

解决方法

appendingPathComponent方法是NSString的一种方法,而不是AnyObject.

改变这一行:

let documentDirectory: AnyObject = path.object(at: 0) as AnyObject

至:

let documentDirectory = path.object(at: 0) as! NSString

但是你应该尝试尽可能多地使用适当的类型.

试试这个:

func returnPDFPath() -> String {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,true)
    let documentDirectory = path.first! as NSString
    let PDFPathFileName = documentDirectory.appendingPathComponent(fileName as String)

    return PDFPathFileName
}

代码假定路径至少有一个值(应该是).

猜你在找的Swift相关文章