从“(_) throws -> Void”类型的抛出函数到非抛出函数类型“([UNNotificationRequest]) -> Void 的无效转换

Invalid conversion from throwing function of type '(_) throws -> Void' to non-throwing function type '([UNNotificationRequest]) -> Void

我正在尝试获取有关本地通知的待处理通知请求。 它抛出我的错误: "Invalid conversion from throwing function of type '(_) throws -> Void' to non-throwing function type '([UNNotificationRequest]) -> Void' "

我的代码是:

var notificationTitle = "\(String(describing: notificationData!["title"]))"
var notificationInterval: Int = notificationData!["interval"] as! Int
let center  =  UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: {(requests) -> Void in
    var notificationExist:Bool = false
    for notificationRequest in requests {
        try{
            var notificationContent:UNNotificationContent = notificationRequest.content
        }
    }

我不确定你的代码的哪一部分出错了,但这行代码不正确:

try{
    var notificationContent:UNNotificationContent = notificationRequest.content
    }

正确的做法是这样的:

do {
    var notificationContent:UNNotificationContent = try notificationRequest.content
}
catch {
print(error)
}

你可能想这样做,

    center.getPendingNotificationRequests(completionHandler: {requests -> () in
        var notificationExist:Bool = false
        for notificationRequest in requests {
            do {
                var notificationContent:UNNotificationContent = try notificationRequest.content
            }
            catch {
                print(error)
            }
        }
    }

问题出在您的 try 块中。因此,您可以如下所示替换它。

guard let notificationContent:UNNotificationContent = try? notificationRequest.content else {
    print("There was an error!")
}