Inter-app communication in iOS using URL scheme

被刻印的时光 ゝ 提交于 2019-12-04 20:09:30

Your error

ViewController().labelToDisplayResult.text = query

ViewController() Create a new instance of ViewController,not the one loaded from storyboard.I guess labelToDisplayResult is an outlet, so it is nil,so you get EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)

This is what I usually do to handle openURL scheme,need to think about two states:

  1. Target App is launched before,so when open url happen,the target app is in background or inactive state
  2. Target App is not launched,so when open url happen,the target app is not running at all

In Appdelegate

class AppDelegate: UIResponder, UIApplicationDelegate {
var openUrl:NSURL? //This is used when to save state when App is not running before the url trigered
var window: UIWindow?


func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    let url = url.standardizedURL
    NSNotificationCenter.defaultCenter().postNotificationName("HANDLEOPENURL", object:url!)
    self.openUrl = url
    return true;
}

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    return true
}
}

Then in the ViewController handle openURL

class ViewController: UIViewController {

@IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
     NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleOpenURL:", name:"HANDLEOPENURL", object: nil)
    let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
    if let url = delegate?.openUrl{
       testLabel.text = url.description 
        delegate?.openUrl = nil 
    }
}
func handleOpenURL(notification:NSNotification){
    if let url = notification.object as? NSURL{
        testLabel.text = url.description
    }
}
deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "HANDLEOPENURL", object:nil)
}

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!