首页 > 解决方案 > 应用程序 openURL 提供无效的 url

问题描述

功能

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

仍然像平常一样被调用,但是当我这样做时:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    do {
        let contentsOfFile = try NSString(contentsOfFile: url.path, encoding: String.Encoding.utf8.rawValue)
        Swift.print("COF \(contentsOfFile)")
    } catch let error {
        Swift.print("error \(error)")
    }
    ...
}

我收到错误“无法打开文件“____”,因为没有这样的文件。”

这曾经在 iOS 12 中工作。我没有对 SceneDelegate 或任何东西做任何事情,所以我不确定它为什么现在给我无效的 URL。

更新:如果我将 Dropbox 中的文件拖到 iOS 模拟器上,它可以工作。如果我从计算机上的其他任何地方拖动文件,它就不起作用。

标签: iosswift

解决方案


该功能open url可用于读取如下文件,

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let stringPath = Bundle.main.path(forResource: "bbc", ofType: "json") // File name 
        let fileUrl = URL(fileURLWithPath: stringPath!)
        let canOpenBool =  application(UIApplication.shared, open: fileUrl)
        print(canOpenBool)
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        do {
            let contentsOfFile = try NSString(contentsOfFile: url.path, encoding: String.Encoding.utf8.rawValue)
            Swift.print("COF \(contentsOfFile)")
             return true
        } catch let error {
            Swift.print("error \(error)")
             return false
        }
    }
}

推荐阅读