2016년 4월 5일 화요일

[ios][swift] AppDelegate에서 UIAlertController 사용

func showAlertWithTitle(title: String, message: String) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler:
            { action in
                switch action.style
                {
                case .Default:
                    print("default")
                case .Cancel:
                    print("cancel")
                case .Destructive:
                    print("destructive")
                }
        }))

        dispatch_async(dispatch_get_main_queue(), {
            self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
        })
    }



showAlertWithTitle(title, message: message)
로 호출하면 된다.

만약 코드 끝부분에 Alert 출력하는 부분에서 dispatch_async(dispatch_get_main_queue(), {} 로 감싸주지 않으면

Warning: Attempt to present <uialertcontroller: 0x125d424d0=""> on <reco_swift_sample .viewcontroller:="" 0x125e4aad0=""> whose view is not in the window hierarchy!

위와 같은 경고가 표시되면서 Alert이 뜨지 않는다.

댓글 없음:

댓글 쓰기