我有一个与我的代码相关的问题:
func isNotificationsEnabled()->Bool{
var isNotificationEnabled = false
center.getNotificationSettings() { (settings) in
switch settings.soundSetting{
case .enabled:
isNotificationEnabled = true
break
case .disabled:
isNotificationEnabled = false
break
case .notSupported:
isNotificationEnabled = false
break
}
}
return isNotificationEnabled
}
此函数在center.getNotificationSettings()
返回结果之前返回结果。有没有办法等待center.getNotificationSettings()
的结果并同步此功能?
答案 0 :(得分:2)
您正在寻找的是iOS中的完成块, 试试这个,
func isNotificationsEnabled(completion:@escaping (Bool)->Swift.Void){
var isNotificationEnabled = false
center.getNotificationSettings() { (settings) in
switch settings.soundSetting{
case .enabled:
isNotificationEnabled = true
completion(isNotificationEnabled)
break
case .disabled:
isNotificationEnabled = false
completion(isNotificationEnabled)
break
case .notSupported:
isNotificationEnabled = false
completion(isNotificationEnabled)
break
}
}
}
用法,
isNotificationsEnabled { (isNotificationEnabled) in
debugPrint(isNotificationEnabled)
}
答案 1 :(得分:2)
这是一个使用完成块的示例,它已经缩减但功能与您的代码相同:
func isNotificationsEnabled(completion:@escaping (Bool)->() ) {
center.getNotificationSettings() { (settings) in
switch settings.soundSetting {
case .enabled:
completion(true)
default:
completion(false)
}
}
}
可以更加简化为必要:
func isNotificationsEnabled(completion:@escaping (Bool)->() ) {
center.getNotificationSettings() { (settings) in
completion (settings.soundSetting == .enabled)
}
}
由于只有.enabled
案例返回true
,因此在所有其他情况下都会使用default
返回false
。顺便说一句:在Swift中break
不需要语句。
并称之为:
isNotificationsEnabled { success in
if success {
print("is enabled")
} else {
print("is disabled")
}
}
答案 2 :(得分:0)
仅供参考,您可以进一步简化:
func isNotificationsEnabled(completionHandler: @escaping (Bool) -> Void) {
center.getNotificationSettings { settings in
completionHandler(settings.soundSetting == .enabled)
}
}
正如其他人指出的那样,它被调用为:
isNotificationsEnabled { enabled in
if enabled {
print("is enabled")
} else {
print("is not enabled")
}
}
答案 3 :(得分:-1)
添加完成处理程序!
func isNotificationsEnabled(completion: (Bool) -> ())->Bool{
var isNotificationEnabled = false
center.getNotificationSettings() { (settings) in
switch settings.soundSetting{
case .enabled:
isNotificationEnabled = true
break
case .disabled:
isNotificationEnabled = false
break
case .notSupported:
isNotificationEnabled = false
break
}
}
return isNotificationEnabled
completion(isNotificationEnabled)
}
然后叫它
isNotificationEnabled() { isNotificationsEnabled in
print(isNotificationsEnabled)
}