Dawid Macura Dawid Macura - 10 days ago 7
iOS Question

Wait for result of async function in iOS

I have a question related to my code:

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
}


This function return result before
center.getNotificationSettings()
returns results. Is there any way to wait for result of
center.getNotificationSettings()
and sync this function?

Answer

What you are looking for is called Completion block in iOS, Try this,

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
            }
        }
    }

Usage,

isNotificationsEnabled { (isNotificationEnabled) in
    debugPrint(isNotificationEnabled)           
}