ios - 如何将数据从通知发送到应用程序

标签 ios swift notifications

我在我的应用程序中使用本教程来获取通知 http://www.appcoda.com/local-notifications-ios8/

每个通知都有操作 - 编辑。我在 viewDidLoad() 方法中为其添加了观察者:

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleModifyListNotification", name: "modifyListNotification", object: nil)

当按下通知中的“编辑”按钮时,应用程序调用此方法:

func handleModifyListNotification() {

    }

对于我使用的分配通知:

func scheduleLocalNotification() {
        var dateComp:NSDateComponents = NSDateComponents()
        dateComp.year = 2015;
        dateComp.month = 02;
        dateComp.day = 24;
        dateComp.hour = 14;
        dateComp.minute = 34;
        dateComp.timeZone = NSTimeZone.systemTimeZone()
        var calender:NSCalendar? = NSCalendar(calendarIdentifier: NSGregorianCalendar)
        var date:NSDate = calender!.dateFromComponents(dateComp)!
        var localNotification = UILocalNotification()
        localNotification.fireDate = fixNotificationDate(date)
        localNotification.alertBody = "Hey, you must go shopping, remember?"
        localNotification.alertAction = "View List"
        localNotification.category = "shoppingListReminderCategory"
      UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    }

但是我如何向这个方法发送数据来知道哪个通知调用了这个方法呢?

最佳答案

声明您的通知,如下所示,

NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleModifyListNotification:", name: "modifyListNotification", object: nil)

选择器中使用冒号

发布您的通知,例如,

NSNotificationCenter.defaultCenter().postNotificationName("modifyListNotification", object: "Your Object Value")

你的函数应该是,

func handleModifyListNotification(notification: NSNotification) {
    NSLog("Object is %@", notification.valueForKey("object") as String!)
}

关于ios - 如何将数据从通知发送到应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712454/

相关文章:

json - 尝试从数组中获取字符串(打开天气图)

arrays - 如何在 Swift 中打印结构的某些元素?

ios - 在 iOS 中将通知从模型发送到 Controller

ios - 如何设置 future 日期的通知时间戳?

ios - 快速切换 View Controller

ios - 登录 Facebook FBSDK 输入错误代码 : 308 in Swift 4. 2

ios - 设置按钮标题时发出警告 uibutton 可能无法响应 -settitle

ios - 最佳实践 - 在 Swift 中对混合对象进行排序

objective-c - NSNotificationCenter 选择器无法与其 NSNotification 一起使用

ios - 在 block 内设置属性是否安全