2016-03-22 2 views
11

私はiOSアプリケーションでPushNotificationを使っています。私はアプリが通知を受け取ったときにUIalertControllerを表示したいと思います。AppendlegateからUIAlertControllerを表示するには

私はAppDelegateに以下のコードを試してみてください。

[self.window.rootViewController presentViewController:alert animated:YES completion:nil]; 

しかしUIAlertcontrollerは、ルートビュー(最初の画面)で、その他の私は警告してしまったのUIViewControllerやアプリのクラッシュのために示しています。

+0

何creashレポート –

+0

しかしUIAlertcontrollerはofcourseのルート・コントローラにアラートを追加している....ルートビューに表示されます。あなたがユーザーに表示されていないコントローラに警告を追加しようとしているので、他の監視コントローラでクラッシュします。 –

+1

はい私は、私がrootviewにuialertcontrollerを追加していて、アクティブなビューではないことを知っています。そして、私の質問は、通知を受け取ったときに、他のuiviewcontrollerのuialertControllerをどのように表示できるかです。 – Rockers23

答えて

42

スウィフトこの

のObjective-C

UIWindow* topWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 
topWindow.rootViewController = [UIViewController new]; 
topWindow.windowLevel = UIWindowLevelAlert + 1; 

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"APNS" message:@"received Notification" preferredStyle:UIAlertControllerStyleAlert]; 

[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK",@"confirm") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 
    // continue your work 

// important to hide the window after work completed. 
// this also keeps a reference to the window until the action is invoked. 
topWindow.hidden = YES; 
}]]; 

[topWindow makeKeyAndVisible]; 
[topWindow.rootViewController presentViewController:alert animated:YES completion:nil]; 

Swift3

let topWindow = UIWindow(frame: UIScreen.main.bounds) 
topWindow.rootViewController = UIViewController() 
topWindow.windowLevel = UIWindowLevelAlert + 1 
let alert = UIAlertController(title: "APNS", message: "received Notification", preferredStyle: .alert) 
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "confirm"), style: .cancel, handler: {(_ action: UIAlertAction) -> Void in 
    // continue your work 
    // important to hide the window after work completed. 
    // this also keeps a reference to the window until the action is invoked. 
    topWindow.isHidden = true 
})) 
topWindow.makeKeyAndVisible() 
topWindow.rootViewController?.present(alert, animated: true, completion: { _ in }) 

を試してみてください10

詳細説明:http://www.thecave.com/2015/09/28/how-to-present-an-alert-view-using-uialertcontroller-when-you-dont-have-a-view-controller/

+0

ありがとう@ Anbu.karthik、それは働いています:) – Rockers23

+0

私はスイフト3のためのUIAlertに別のボタンを追加する方法はありません –

+0

UIAlertActionのオブジェクトを作成し、アクションを処理します。 –

関連する問題