はじめに
NSAlert
を用いると警告のポップアップを出すことができますが、messageText
とinformativeText
を指定する方法だとアイコンが警告用になりません。
let alert = NSAlert()
alert.informativeText = "Uploaded file is broken"
alert.messageText = "Retry to upload the file."
alert.runModal()
そこで、NSError
を使うと楽に警告用のポップアップを表示できます。
1. 普通に表示
let userInfo: [String: Any] = [
NSLocalizedDescriptionKey: "Uploaded file is broken",
NSLocalizedRecoverySuggestionErrorKey: "Retry to upload the file."
]
let error = NSError(domain: "HogeDomain", code: 0, userInfo: userInfo)
let alert = NSAlert(error: error)
alert.runModal()
2. より詳細なエラー情報を付加して表示
let userInfo: [String: Any] = [
NSLocalizedFailureErrorKey: "API Error:\t",
NSLocalizedFailureReasonErrorKey: "duration is too short",
NSLocalizedRecoverySuggestionErrorKey: "The video file length should be 5 seconds or more."
]
let error = NSError(domain: "HogeDomain", code: 0, userInfo: userInfo)
let alert = NSAlert(error: error)
alert.runModal()
3. さらにボタンを押した時の処理を追加する
let userInfo: [String: Any] = [
NSLocalizedDescriptionKey: "Uploaded file is broken",
NSLocalizedRecoverySuggestionErrorKey: "Retry to upload the file."
]
let error = NSError(domain: "HogeDomain", code: 0, userInfo: userInfo)
let alert = NSAlert(error: error)
alert.addButton(withTitle: "Retry")
alert.addButton(withTitle: "Cancel")
let result = alert.runModal()
if result == .alertFirstButtonReturn {
// Retry の処理
print("Retry")
}