Swift:DiskImageCache:无法解析旧目录的绝对路径

时间:2015-01-08 19:36:17

标签: ios swift

我正在尝试在我正在构建的应用的视图中加载本地PDF。我将PDF加载到images.cassetes文件夹中。我也进入了目标>信息>文档类型并添加PDF作为文档类型:com.adobe.pdf。

我正在使用Xcode 6.1.1和iOS 8.

以下是我的View Controller的代码:

 import UIKit

 class DisplayFirstStepsViewController: UIViewController {

    @IBOutlet weak var currentDocument: UIWebView!

    var currentFirstSteps : FirstStep?

    override func viewDidLoad() {
    super.viewDidLoad()

    var pdfLoc = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource((named: currentFirstSteps!.filename), ofType:"pdf")!)
    var request = NSURLRequest(URL: pdfLoc!);



    self.currentDocument.loadRequest(request);


    navigationController?.hidesBarsOnSwipe = true

    // Do any additional setup after loading the view.
}

它在模拟器中工作但在实际手机上没有。然后我点击了产品>干净,现在我收到这个错误:

致命错误:在解包可选值时意外发现nil

我看到使用此代码修复原始错误的位置:

NSString *path = [[NSBundle mainBundle] pathForResource:@"b777normalprocedures"     ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:targetURL];
_webView loadData:pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

但是,我不知道如何从Objective-c将其转换为swift或者如何清理我的代码以便按原样工作。任何和所有的帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

func loadUrl(request:NSURL){
    currentDocument.loadRequest(NSURLRequest(URL: request))
}
func loadData(data:NSData){
    currentDocument.loadData(data, MIMEType: "application/pdf", textEncodingName: "utf-8", baseURL: nil)
}
if let pdfFileBundleUrl = NSBundle.mainBundle().URLForResource("pdfFileName", withExtension: "pdf") {
    loadUrl(pdfFileBundleUrl)
}

if let targetURL = NSBundle.mainBundle().URLForResource("b777normalprocedures", withExtension: "pdf") {
    if let pdfData = NSData(contentsOfURL:targetURL) {
        loadData(pdfData)
        println("Successfully loaded data" )
    } else {
        println("Failed to loading data")
    }
}


let docsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
docsUrl.absoluteURL!
docsUrl.absoluteString!
docsUrl.path!

代码示例

您还可以将其缓存为pdf,因此不会将其下载两次,如下所示:

首先将这两个变量添加到AppDelegate.swift

//
//  AppDelegate.swift
//  pdfSample

import UIKit
var loaded = false
var cachedData:NSData? = nil

//

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var wv: UIWebView!

    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL

    func loadData(data:NSData){
        cachedData = data
        wv.loadData(data, MIMEType: "application/pdf", textEncodingName: "utf-8", baseURL: nil)

    }
    func loadPDF(link:String){
        if let pdfOnlineUrl = NSURL(string: link) {
            if let downloadedData = NSData(contentsOfURL: pdfOnlineUrl) {
                let newFolderUrl = documentsUrl.URLByAppendingPathComponent("pdfs")
                var err: NSErrorPointer = nil
                if NSFileManager.defaultManager().createDirectoryAtPath(newFolderUrl.path!, withIntermediateDirectories: true, attributes: nil, error: err) {
                    println("directory successfully created and/or opened")
                    let pdfDestinationUrl = newFolderUrl.URLByAppendingPathComponent(pdfOnlineUrl.lastPathComponent!)
                    if downloadedData.writeToURL(pdfDestinationUrl, atomically: true) {
                        println("pdf saved")
                        if let data = NSData(contentsOfURL: pdfDestinationUrl) {
                            loadData(data)
                            let pdfFile = pdfDestinationUrl.lastPathComponent?.stringByDeletingPathExtension
                            println("Successfully loaded data pdf file named " + pdfFile! )
                            loaded = true
                        } else {
                            println("Failed to load data pdf file: \(pdfDestinationUrl.lastPathComponent?.stringByDeletingPathExtension)")
                        }
                    } else {
                        println("file not saved")
                    }
                } else {
                    println("error creating destination folder / destination folder not found")
                }
            } else {
                println("Failed to download font from URL: " + pdfOnlineUrl.description)
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       if !loaded {
       loadPDF("https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/SwiftStandardLibraryReference.pdf")
        } else {
            loadData(cachedData!)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}