如何在Today扩展中发送和接收数据
我想开发一个iOS应用程序,它有一个通知中心的Widget,但我不知道如何在View Controller和And Today Extension之间发送和接收数据(传递数据)。
我试图使用结构,但它不起作用,我也使用了应用程序组,但我不想使用此方法。
let shared = NSUserDefaults(suiteName: "group.Demo.Share-Extension-Demo.mahdi") shared?.setObject("Hello", forKey: "kkk")
除NSUserDefaults外,您还可以使用NSNotificationCenter在任何地方发送或接收数据。
您需要将观察者设置在可以接收数据的位置,如下所示:
override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataReceived:", name: "SpecialKey", object: nil) }
Funciton捕获数据:
func dataReceived(notification: NSNotification) { //deal with notification.userInfo println(notification.userInfo) println("Received Data") }
您需要从需要发送数据的位置定义NSNotificationCenter:
NSNotificationCenter.defaultCenter().postNotificationName("SpecialKey", object: nil, userInfo: ["MyData": "Demo"])
参考文献:
NSNotificationCenter的完整指南
希望能帮助到你!
http://moreindirection.blogspot.in/2014/08/nsnotificationcenter-swift-and-blocks.html
对于那些没有找到实现调用function或按钮的人来自App Extension(Widget)的人:
注意 :这是使用Swift
注2 :将NSNotification和方法的名称替换为您的实现
- 首先,创建NotificationCenter post方法(在Swift 2.0中 – NSNotification Center)
在App Delegate类中创建方法 –
var scheme: String! var host: String!
然后,在类的底部添加以下函数(在最后一个之后):
func application(_ app: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { scheme = url.scheme host = url.host NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"), object: nil) return true }
-
在ViewController类中,要执行函数或单击Widget的语句,请在
super.viewDidLoad()
添加以下内容:NotificationCenter.default.addObserver(self,selector: #selector(self.YOUR_METHOD_NAME), name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"), object: nil)
并且您要调用的方法:
func YOUR_METHOD_NAME(notification: NSNotification) { let appDelegate = UIApplication.shared.delegate as! AppDelegate if appDelegate.scheme != nil { startRecording() } }
-
我假设您已经创建了窗口小部件目标,以及它的视图。 将其添加到您希望处理点击的TodayViewController中的按钮:
@IBAction func openApp(_ sender: UIButton) { openApp() }
以及URl Scheme处理开放应用程序的function:
func openApp(){ let myAppUrl = NSURL(string: "YOUR_URL_SCHEME://YOUR_HOST_NAME")! extensionContext?.open(myAppUrl as URL, completionHandler: { (success) in if (!success) { self.textView.text = "There was a problem opening app!" } }) }
对于YOUR_URL_SCHEME,添加您在Info.plist中指定的方案,如果您没有,请转到此链接并按照说明操作: 将URL方案添加到Xcode
对于YOUR_HOST_NAME,您可以将其删除,并且只能通过url方案打开应用。
快乐的编码!