質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

2956閲覧

iOS 通知ダイアログを許可したタイミングでviewDidLoad()を再度読ませたい

oooeee

総合スコア9

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/04/25 10:48

編集2019/04/26 02:45

表題の通りです。

webviewでデフォルトのURLを指定しているのですが、初回起動時の通知ダイアログがある場合にルートパス(/)に飛んでしまいます。

通知ダイアログ

想定している動きとしてはルートパスのあとにtokenを埋め込む形です(/tokenの文字列〜)。

【ViewController.swift】

swift

1 override func viewDidLoad() { 2 super.viewDidLoad() 3 // Do any additional setup after loading the view, typically from a nib. 4 5 let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate 6 appDelegate.viewController = self 7 8 let fcmToken = UserDefaults.standard.string(forKey: "fcmToken") ?? "" 9 print("トークン取得情報: (fcmToken)") 10 11 let urlString = "localhost:8080/(fcmToken)" 12 let urlRequest = URLRequest(url: URL(string: urlString)!) 13 self.browserWebView.load(urlRequest) 14 } 15 16 @IBAction func goBack(_ sender: Any) { 17 self.browserWebView.goBack() 18 } 19 @IBAction func goForward(_ sender: Any) { 20 self.browserWebView.goForward() 21 } 22 @IBAction func reload(_ sender: Any) { 23 self.browserWebView.reload() 24 } 25} 26

これを回避するためにAppDelegateのapplicationDidBecomeActiveでviewDidLoad()を再読込するように処理を入れました。

【AppDelegate.swift】

swift

1import UIKit 2import Firebase 3import FirebaseMessaging 4import UserNotifications 5 6@UIApplicationMain 7class AppDelegate: UIResponder, UIApplicationDelegate { 8 9 var window: UIWindow? 10 var viewController: ViewController! 11 12 13 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 14 // Override point for customization after application launch. 15 FirebaseApp.configure() 16 17 Messaging.messaging().delegate = self 18 19 if #available(iOS 10.0, *) { 20 // For iOS 10 display notification (sent via APNS) 21 UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate 22 23 let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] 24 UNUserNotificationCenter.current().requestAuthorization( 25 options: authOptions, 26 completionHandler: {_, _ in }) 27 } else { 28 let settings: UIUserNotificationSettings = 29 UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 30 application.registerUserNotificationSettings(settings) 31 } 32 33 application.registerForRemoteNotifications() 34 35 let defaults = UserDefaults.standard 36 let dic = ["firstLaunch": true] 37 defaults.register(defaults: dic) 38 39 return true 40 } 41 42 func applicationWillResignActive(_ application: UIApplication) { 43 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 44 // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 45 } 46 47 func applicationDidEnterBackground(_ application: UIApplication) { 48 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 49 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 50 } 51 52 func applicationWillEnterForeground(_ application: UIApplication) { 53 // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 54 } 55 56 func applicationDidBecomeActive(_ application: UIApplication) { 57 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 58 59 let defaults = UserDefaults.standard 60 if defaults.bool(forKey: "firstLaunch") { 61 // Some Process will be here 62 let appDelegate = UIApplication.shared.delegate as! AppDelegate 63 appDelegate.viewController?.viewDidLoad() 64 65 // off the flag to know if it is first time to launch 66 defaults.set(false, forKey: "firstLaunch") 67 } 68 } 69 70 func applicationWillTerminate(_ application: UIApplication) { 71 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 72 } 73 74 75} 76 77extension AppDelegate : MessagingDelegate { 78 // [START refresh_token] 79 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { 80 print("ファイアベースに登録するやつ: (fcmToken)") 81 82 let dataDict:[String: String] = ["token": fcmToken] 83 NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict) 84 85 //save token 86 UserDefaults.standard.set(fcmToken, forKey: "fcmToken") 87 } 88 // [END refresh_token] 89 // [START ios_10_data_message] 90 // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. 91 // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true. 92 func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { 93 print("Received data message: (remoteMessage.appData)") 94 } 95 // [END ios_10_data_message] 96} 97 98

シミュレーター、ipad実機でうまく動作(ダイアログを閉じるとviewDidLoad()が再読込された)したので問題ないなと思っていたのですが、どうやらapplicationDidBecomeActiveが呼ばれるときと呼ばれないときがあるようでうまく動作しなくなってしまいました。

手元のシミュレーター、ipadでも確認しましたが、うまくいくときもあればうまくいかないときもあって頭を抱えています。
※アプリをアンインストール→ビルドの繰り返しで確認

こういった問題があるので、通知ダイアログで許可(Allow)をしたタイミングでviewDidLoad()を読み直したいのですが、どういったコードをどこに書けばいいのか分かりませんでした。
https://qiita.com/tokorom/items/6c6864fa8e841e50e37bの記事を参考にしました)

ダイアログの処理について詳しい方にご教示をいただきたいです、よろしくお願いいたします。
ダイアログは関係ありませんでした。

最初のアプリ立ち上げ時にfcmTokenの取得前にwebViewを読み込んでいるのが原因でした。
AppDelegateでfcmTokenを取得している箇所をviewDidLoadの前に読み込むことができれば解決すると思うのですが、可能でしょうか?

追記:起動ログのスクリーンショット
イメージ説明

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

生成されたときに呼ばれる viewDidLoad ではなく、
画面に表示される直前直後に呼ばれる viewWillAppear, viewDidAppear を利用すれば良いと考えます。

特定の処理の後に何かをしたい場合。
【Swift】NotificationCenterの使い方

投稿2019/04/25 11:49

編集2019/04/27 02:00
dsuzuki

総合スコア1682

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

oooeee

2019/04/26 02:08

dsuzuki様 ご回答ありがとうございます。 viewDidLoadの処理をviewWillAppear, viewDidAppearでそれぞれ試してみましたがうまくいきませんでした。 そこで、調査したところAppDelegate.swiftで定義しているfcmTokenの取得が、viewDidLoad()のあとで読み込まれていました。 ※ログのスクショを質問に貼ります delegateのfcmTokenの取得をviewDidLoadまたはiewWillAppear, viewDidAppearの前に読み込ませることはできないでしょうか?
dsuzuki

2019/04/27 02:02

fcmTokenの取得をviewDidLoad等の前に呼ばせることを考えるよりも、NotificationCenterを利用して、fcmTokenが呼ばれたことをViewControllerに通知して、webViewを更新する方法はどうでしょうか。
oooeee

2019/04/29 00:27

dsuzuki様 そのような方法があるのですね!調べて試してみたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問