[英]get string of text from url scheme works in appdelegate but not in viewcontroller
[英]loading url from scheme not processing first time - appdelegate vs viewcontroller
我的应用程序成功打开并将参数(来自 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
}
视图控制器.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,则不会打印文本。 当我单击主页按钮并再次单击应用程序时,它会打印。
Ps 我是 swift 的新手,还不确切知道首先加载/处理哪个类(AppDelegate 或 ViewContoller)。 我已经尝试了将近 5 个小时来解决这个问题,第二次仍然保持打印。
复制您的代码
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
}
@SalihanPamuk 我认为这是由于appWillEnterForeground()
方法。 UIApplication.willEnterForegroundNotification
- 这是发布应用程序进入前台的第一个通知。
由于您已经注册了一个监听器来监听这个通知, appWillEnterForeground()
方法将在appWillEnterForeground()
调用之前调用
application(_ app: UIApplication, open url: URL, options:
[UIApplication.OpenURLOptionsKey : Any] = [:]) - method.
尝试实现 appDelegate 的
func applicationWillEnterForeground(_ application: UIApplication) {
// Do your stuffs here
}
或者,如果您想在使用任何 URL 设置打开应用程序后显示任何特定的 ViewController,请在
func application(_ app: UIApplication, open url: URL, options:
[UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// implemet your code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.