![](/img/trans.png)
[英]Is inter-app communication possible without using URL Scheme in iOS?
[英]Inter-app communication in iOS using URL scheme
我有两个测试应用程序: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,该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
实例,而不是从情节labelToDisplayResult
加载的实例。我猜labelToDisplayResult
是一个插座,所以它为nil,所以您得到EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)
这是我通常要做的处理openURL方案的工作,需要考虑以下两种状态:
在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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.