简体   繁体   English

通过URL方案打开完全退出的应用未在iOS中从postNotificationName调用该函数

[英]Open fully quitted app from URL scheme did not call the function from postNotificationName in iOS

Here I have set the code for URL scheme: 在这里,我为URL方案设置了代码:

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    if let userUrl = String(url) as String? {
        print("\(userUrl)")
        if (userUrl == "count://fromClipBoard") {
            NSNotificationCenter.defaultCenter().postNotificationName("com.getContentFromClipBoard", object: self)
        }
    }
    return false
}

And add the following code to my ViewController : 并将以下代码添加到我的ViewController

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setContentFromClipBoard", name: "com.getContentFromClipBoard", object: nil)

    //............
}

func setContentFromClipBoard() {
    tv.text = "WAHAHA"

    if let clipBoard = UIPasteboard.generalPasteboard().string {
        tv.text = clipBoard
    }
}

And when my app is not fully quitted, com.getContentFromClipBoard called well and tv.text become clipBoard . 当我的应用程序没有完全退出时, com.getContentFromClipBoard调用很好,而tv.text成为clipBoard

However, when I fully quit the app and then use this URL scheme, the com.getContentFromClipBoard isn't get called and tv.text remain empty. 然而,当我完全退出应用程序,然后使用这个URL方案中, com.getContentFromClipBoard不会被调用和tv.text保持为空。

So how can I fix it? 那么我该如何解决呢? Thanks! 谢谢!

Fixed by checking UIApplicationLaunchOptionsURLKey too inside didFinishLaunchingWithOptions . 通过在didFinishLaunchingWithOptions内部检查UIApplicationLaunchOptionsURLKey修复。

(Delaying is waiting the view to load) (延迟正在等待视图加载)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    if let userUrl = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
            if (userUrl.absoluteString == "count://fromClipBoard") {
                NSNotificationCenter.defaultCenter().postNotificationName("com.getContentFromClipBoard", object: self)
            }
        })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM