在通知标题中显示功能结果(Swift 3,iOS10)

Display result of function in notification title (Swift 3, iOS10)

我在 ios10 中从我的 Swift 3 应用程序触发了一个本地通知,虽然我可以让通知正常启动,但我正在尝试传递一个变量(这发生了是从函数返回的值)作为通知标题的一部分。它没有显示该变量的内容,而是显示为“(函数)”。

我在应用程序本身内使用与标签文本相同的变量,没有任何问题。

我创建了以下 class 和 class 函数来安排通知:

class notificationController {

class func scheduleNotification(at date: Date, header: String, body: String) {

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: header, arguments: nil)
    content.body = body
    content.sound = UNNotificationSound.default()

    let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("error: \(error)")
        }
    }


}

然后我在与主屏幕关联的视图控制器的 viewdidload() 函数中定义要传递给此函数的变量,然后调用 scheduleNotification 函数:

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
        let strDate = "25/01/2017 21:21:00"
        let notificationDate = dateFormatter.date(from: strDate)
        let dayNumber = String(describing: (playerArray[0]?.calculateDays)!)
        let header = "Welcome to day \(dayNumber) of your life"
        var body : String = ""

    if(infoArray.count > 0) {
        body = (infoArray[0]?.text)!
   } else {body = "Doesn't it feel great to be alive?"}

        notificationController.scheduleNotification(at: notificationDate!, header: header, body: body)

PlayerArray 是一个包含一个 Player CoreData object 的数组。我在播放器 class 中创建了以下函数来计算播放器的年龄:

public class Player: NSManagedObject {

func calculateDays() -> Int {

    let currentCalendar = Calendar.current
    guard let dob = currentCalendar.ordinality(of: .day, in: .era, for: self.dob as! Date) else {
        return 0
    }
    guard let today = currentCalendar.ordinality(of: .day, in: .era, for: Date()) else {
        return 0
    }
    let days = today - dob

    return days
}

}

dayNumber 变量不显示的任何原因?我觉得这是我错过的显而易见的事情。任何想法都会很神奇。

你需要用()

调用函数

改变这个:

    let dayNumber = String(describing: (playerArray[0]?.calculateDays)!)

对此:

    let dayNumber = String(describing: (playerArray[0]?.calculateDays())!)