Moh*_*oha 5 cocoa-touch uiviewcontroller ios swift today-extension
我想开发一个具有通知中心小部件的 iOS 应用程序,但我不知道应该如何在视图控制器和今日扩展之间发送和接收数据(传递数据)。
我尝试使用结构,但它不起作用,而且我也使用应用程序组,但我不想使用这种方法。
let shared = NSUserDefaults(suiteName: "group.Demo.Share-Extension-Demo.mahdi")
shared?.setObject("Hello", forKey: "kkk")
Run Code Online (Sandbox Code Playgroud)
除了 NSUserDefaults 之外,您还可以使用 NSNotificationCenter 在任何地方发送或接收数据。
您需要设置可以接收数据的观察者,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataReceived:", name: "SpecialKey", object: nil)
}
Run Code Online (Sandbox Code Playgroud)
捕获数据的函数:
func dataReceived(notification: NSNotification) {
//deal with notification.userInfo
println(notification.userInfo)
println("Received Data")
}
Run Code Online (Sandbox Code Playgroud)
并且您需要从需要发送数据的位置定义 NSNotificationCenter:
NSNotificationCenter.defaultCenter().postNotificationName("SpecialKey", object: nil, userInfo: ["MyData": "Demo"])
Run Code Online (Sandbox Code Playgroud)
参考:
希望能帮助到你!
http://moreindirection.blogspot.in/2014/08/nsnotificationcenter-swift-and-blocks.html
| 归档时间: |
|
| 查看次数: |
4398 次 |
| 最近记录: |