OBJECTIVE-C:
- In Alert.h
(void)showAlertWithTitle:(NSString *)title
message:(NSString* _Nullable)message
defaultPrompt:(NSString *)defaultPrompt
optionalPrompt:(NSString* _Nullable)optionalPrompt
defaultHandler:(nullable void(^)(UIAlertAction *))defaultHandler
optionalHandler:(nullable void(^)(UIAlertAction *))optionalHandler;
In Alert.m
(void)showAlertWithTitle:(NSString *)title message:(NSString* _Nullable)message defaultPrompt:(NSString *)defaultPrompt optionalPrompt:(NSString* _Nullable)optionalPrompt defaultHandler:(nullable void(^)(UIAlertAction *))defaultHandler optionalHandler:(nullable void(^)(UIAlertAction *))optionalHandler {
// Executing the method in the main thread, since its involving the UI updates.
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:defaultPrompt style:UIAlertActionStyleDefault handler:defaultHandler]];
if (optionalPrompt) {
[alert addAction:[UIAlertAction actionWithTitle:optionalPrompt style:UIAlertActionStyleCancel handler:optionalHandler]];
}
[[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alert animated:true completion:nil];
}); }
SWIFT 4.2:
Просто создайте новый файл swift с именем Alert.swift и определите обобщенную версию AlertController
в нем.Таким образом, вы можете использовать его в любом месте проекта, просто позвонив Alert.showErrorAlert("", title: "")
import UIKit
import os.log
class Alert {
/// Display the given error message as an alert pop-up
/// - parameter errorMessage: The error description
/// - parameter title: The title of the error alert
class func showErrorAlert(_ errorMessage: String, title: String?) {
let alert = UIAlertController(title: title ?? "Error", message: errorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
guard let rootView = UIApplication.shared.keyWindow?.rootViewController else {
os_log("Cannot show alert in the root view", log: .default, type: .error)
return
}
rootView.present(alert, animated: true, completion: nil)
}
}