UIApplication.shared.open(_ url: URL,etc.) 没有打开任何东西

UIApplication.shared.open(_ url: URL,etc.) doesn't open anything

我已将 "instagram" 添加到我的 Info.plist 文件中的 LSApplicationQueriesSchemes,但是当调用以下函数时它仍然无法打开 safari 和 instagram:

func openinstagram () {
    let instaurl = URL(fileURLWithPath: "https://www.instagram.com/(myusername)/?hl=de")
    if UIApplication.shared.canOpenURL(instaurl) {
        UIApplication.shared.open(instaurl, options: [:] ) { (sucess) in
            print("url opened")
        }
    }
}

除了日志中的"url opened"

,它什么也没告诉我

解决这个问题的方法是什么? 提前谢谢你

你用错了API

  • URL(fileURLWithPath 适用于以 /
  • 开头的文件系统 URL
  • URL(string 适用于以方案 (https://file://)
  • 开头的 URL

myusername 的字符串插值看起来不对(查询问号前缺少反斜杠和多余的斜杠)。

    if let instaurl = URL(string: "https://www.instagram.com/\(myusername)?hl=de"),
       UIApplication.shared.canOpenURL(instaurl) { ...

你可以试试这个。

URL(fileURLWithPath:) 用于获取以 /

开头的文件

URL(string:) 是创建网站 url

func openinstagram () {
    if let instaurl = URL(string: "https://www.instagram.com/(myusername)/?hl=de"),
        UIApplication.shared.canOpenURL(instaurl) {

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(instaurl)
        } else {
            UIApplication.shared.openURL(instaurl)
        }
    }
}