LoginSignup
2
1

More than 3 years have passed since last update.

Swift:NSErrorを使って楽にNSAlertを表示する

Last updated at Posted at 2020-08-03

はじめに

NSAlertを用いると警告のポップアップを出すことができますが、messageTextinformativeTextを指定する方法だとアイコンが警告用になりません。

let alert = NSAlert()
alert.informativeText = "Uploaded file is broken"
alert.messageText = "Retry to upload the file."
alert.runModal()

例1.png

そこで、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.png

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.png

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

例4.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1