【问题标题】:loading url from scheme not processing first time - appdelegate vs viewcontroller从第一次未处理的方案加载 url - appdelegate vs viewcontroller
【发布时间】:2019-09-16 18:07:07
【问题描述】:

我的应用程序已成功打开并将参数(来自 URL 方案,即 myApp://sometextToPrint)设置为 AppDelegate 类中的一个变量,但每当我想处理它们时,它在应用程序运行时第一次失败从该 URL 打开。我在前台检查器中有一个应用程序,它调用用于打印给定参数的函数,但不知何故,看起来AppDelegate 的加载时间比视图在第一次加载时无法打印参数的视图要晚。

我的代码如下:

AppDelegate.m

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

let geturl = url.host?.removingPercentEncoding;
UserDefaults.standard.set(geturl, forKey: "DeepLinkUrl")
return true
}

ViewController.m

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground),name: UIApplication.willEnterForegroundNotification, object: nil)

}

@objc func appWillEnterForeground() {
    print("app on foreground")
    let user = UserDefaults.standard
    if user.url(forKey: "DeepLinkUrl") != nil {

    let str = user.value(forKey: "DeepLinkUrl") as! String
    print(str) //this is printed on the second time when I click home button and open app again
    }
}

例如,如果我进入 Safari 并点击以下 URL:myApp://printthistext,则不会打印文本。当我单击主页按钮并再次单击应用程序时,它会打印出来。

附:我是 swift 的新手,还不知道首先加载/处理哪个类(AppDelegate 或 ViewContoller)。我已经尝试了将近 5 个小时来解决此问题,但仍在第二次打印。

【问题讨论】:

  • 好吧,每当应用打开首先调用的 appdelegate 类时
  • ViewController 第一次没有取变量真的很奇怪...

标签: ios swift viewcontroller appdelegate url-scheme


【解决方案1】:

复制你的代码
func application(_ app: UIApplication, open url: URL, 
    options: [UIApplication.OpenURLOptionsKey : Any] = [:]) 
    -> Bool {

进入

func application(_ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) 
    -> Bool {

在该方法中,检查launchOptions。如果它包含 url 键,则获取该值 - 并返回 false

if let url = launchOptions[.url] as? URL {
    let geturl = url.host?.removingPercentEncoding
    UserDefaults.standard.set(geturl, forKey: "DeepLinkUrl")
    return false
}

【讨论】:

  • 这是 iOS
【解决方案2】:

@SalihanPamuk 我认为这是由于appWillEnterForeground() 方法。 UIApplication.willEnterForegroundNotification - 这是第一个发布应用程序即将进入前台的通知。

由于您已经注册了一个监听器来监听这个通知,appWillEnterForeground() 方法将在 appDelegate 之前调用

application(_ app: UIApplication, open url: URL, options: 
[UIApplication.OpenURLOptionsKey : Any] = [:]) - method.

尝试实现appDelegate的

func applicationWillEnterForeground(_ application: UIApplication) {
    // Do your stuffs here 
}

或者,如果您想在使用任何 URL 设置打开应用程序后显示任何特定的 ViewController,请使用用于在其中显示该 ViewController 的代码

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

// implemet your code here 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 2015-01-20
    • 2017-09-03
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多