使用URL方案

时间:2015-09-28 13:39:51

标签: ios swift url fatal-error

我有两个测试应用程序:App1& APP2。

App1从文本字段中获取String并触发方法:

@IBAction func openApp(sender: AnyObject) { 
    let url1 = ("app2://com.application.started?displayText="+textToSend.text!)
    let url2 = url1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
    UIApplication.sharedApplication().openURL(NSURL(string: url2!)!)
}

实际打开的App2只有标签,应该更改为通过url发送的文本,代码在AppDelegate.swift中:

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    let url = url.standardizedURL
    let query = url?.query
    ViewController().labelToDisplayResult.text = query
    return true;
}

不幸的是,我试图将URL的结果传递给实际标签的行给了我这个错误:

EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)

但是我确实拥有App2中的所有数据,因为我可以在调试器中看到它们的值:

url NSURL   "app2://com.application.started?displayText=564315712437124375" 0x00007fa4e3426320
query   String? "displayText=564315712437124375"

我知道为什么会收到此错误?

...谢谢

1 个答案:

答案 0 :(得分:7)

您的错误

ViewController().labelToDisplayResult.text = query

ViewController()创建ViewController的新实例,而不是从storyboard加载的实例。我猜labelToDisplayResult是一个插座,所以它是零,所以你得到EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)

这是我通常做的处理openURL方案,需要考虑两种状态:

  1. 目标应用程序之前已启动,因此当打开网址时,目标应用程序处于后台或非活动状态
  2. 目标应用未启动,因此当打开网址时,目标应用根本没有运行
  3. 在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
    }
    }
    

    然后在ViewController句柄中打开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)
    }
    
    }