Swift - 如何返回一个bool闭合。

问题描述 投票:0回答:1

我想写一个返回Bool的函数。

func registerForPushNotifications() -> (Bool) -> Void {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        [weak self] granted, error in
        return { granted }
    }
}

但我得到了这个错误。

Cannot convert return expression of type 'Void' to return type '(Bool) -> Void'

我做错了什么?

ios swift push-notification closures unusernotificationcenter
1个回答
1
投票

你的函数返回类型很奇怪。我认为你想做的是获得一个回调,其结果是设备是否被授权接收推送通知。

你应该把下面的内容改成

func registerForPushNotifications() -> (Bool) -> Void {
   // Your implementation
}

改成

func registerForPushNotifications(completion: (Bool) -> Void) {
   UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error in
      completion(granted)
   }
}

这样一来,你就可以调用 registerForPushNotifications 与您希望在推送权限确定后运行的关闭。

registerForPushNotifications { granted in
  // Do something
}
© www.soinside.com 2019 - 2024. All rights reserved.