ref – http://stackoverflow.com/questions/24297273/openurl-not-work-in-action-extension
xcode 8.2.1, ios 10.2, swift 3
File > New > Project > Create Single App
Then, click on your project (blue project icon):
File > New > Target > iMessage Extension
Parent App
AppDelegate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { print("url.scheme - \(url.scheme)") print("url.absoluteString - \(url.absoluteString)") print("url.absoluteURL - \(url.absoluteURL)") print("url.description - \(url.description)") print("url.debugDescription - \(url.debugDescription)") let queryItems = URLComponents(string: url.absoluteString)?.queryItems let param1 = queryItems?.filter({$0.name == "myParam"}).first if let temp = param1 { // we first unwrap param1, when its valid, we can use it to access its property value // value is optional itself, i decided to use force unwrap here let topWindow = UIWindow(frame: UIScreen.main.bounds) topWindow.rootViewController = UIViewController() topWindow.windowLevel = UIWindowLevelAlert + 1 let alert = UIAlertController(title: "APNS", message: "received Notification - \(temp.value!)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "confirm"), style: .cancel, handler: {(_ action: UIAlertAction) -> Void in // continue your work // important to hide the window after work completed. // this also keeps a reference to the window until the action is invoked. topWindow.isHidden = true })) topWindow.makeKeyAndVisible() topWindow.rootViewController?.present(alert, animated: true, completion: { _ in }) } return true } |
iMessage Extension
Throw a button in your xib, and to a handler like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@IBAction func test(_ sender: Any) { if let url = NSURL(string: "iMessageTest://iMessageTest?myParam=myValue") { self.extensionContext?.open(url as URL, completionHandler: { (success) in if(success) { print("yay") } }) } } //end of test |
If you’re not in UIViewController, you can go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
static func openwithCode(code: String, completion: @escaping (_ result: Bool, _ urlStr: String) -> Void ) { if let url = URL(string: "yourApp://yourApp?code=\(someCode)") { if #available(iOS 10.0, *) { if(UIApplication.shared.canOpenURL(url)) { UIApplication.shared.open(url, completionHandler: {(success) in completion(success, url.absoluteString) //this needs to stick around }) } } else { // < iOS 10.0 completion(UIApplication.shared.openURL(url), url.absoluteString) } } } |