使用URL方案在iOS中进行应用程序间通信
我有两个测试应用程序: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"
知道我为什么会收到这个错误吗?
谢谢…
你的错误
ViewController().labelToDisplayResult.text = query
ViewController()
创建一个新的ViewController
实例,而不是从storyboard加载的实例。我猜labelToDisplayResult
是一个sockets,所以它是零,所以你得到EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)
这是我通常做的处理openURL方案,需要考虑两种状态:
- 目标应用程序之前启动,因此当打开URL时,目标应用程序处于后台或非活动状态
- 目标应用程序未启动,因此当打开URL时,目标应用程序根本不运行
在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) } }