From 799a4cad717ba04757f6212864c9fa69cb2bd450 Mon Sep 17 00:00:00 2001
From: Hadrien De Sousa <hadrien.desousa@savoirfairelinux.com>
Date: Wed, 12 Jul 2017 16:32:19 -0400
Subject: [PATCH] launch: fix account loading

This commit fixes accounts loading at launch that displayed the
smartlist even if there was no accounts

Change-Id: I87e3aeffa9e780d7a1ff43f4511a331a0d5d987f
---
 Ring/Ring/AppDelegate.swift                   | 37 ++++++++++++++++++-
 .../Constants/Generated/Storyboards.swift     | 11 +++++-
 Ring/Ring/Info.plist                          |  2 -
 .../MainTabBar/MainTabBarViewController.swift |  8 ----
 Ring/Ring/Resources/LaunchScreen.storyboard   |  6 +--
 Ring/Ring/Resources/Main.storyboard           |  4 +-
 Ring/Ring/Services/AccountsService.swift      |  9 ++++-
 .../CreateRingAccountViewController.swift     |  3 ++
 8 files changed, 62 insertions(+), 18 deletions(-)

diff --git a/Ring/Ring/AppDelegate.swift b/Ring/Ring/AppDelegate.swift
index 03026bc52..575fcf958 100644
--- a/Ring/Ring/AppDelegate.swift
+++ b/Ring/Ring/AppDelegate.swift
@@ -22,6 +22,7 @@
 import UIKit
 import RealmSwift
 import SwiftyBeaver
+import RxSwift
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -33,8 +34,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
     static let conversationsService = ConversationsService(withMessageAdapter: MessagesAdapter())
     private let log = SwiftyBeaver.self
 
+    fileprivate let disposeBag = DisposeBag()
+
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
 
+        self.window = UIWindow(frame: UIScreen.main.bounds)
+
         // initialize log format
         let console = ConsoleDestination()
         console.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d $C$L$c: $M"
@@ -42,6 +47,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
 
         SystemAdapter().registerConfigurationHandler()
         self.startDaemon()
+        self.loadAccounts()
         return true
     }
 
@@ -66,7 +72,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
 
         do {
             try AppDelegate.daemonService.startDaemon()
-            AppDelegate.accountService.loadAccounts()
+
         } catch StartDaemonError.initializationFailure {
             log.error("Daemon failed to initialize.")
         } catch StartDaemonError.startFailure {
@@ -87,4 +93,33 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
             log.error("Unknown error in Daemon stop.")
         }
     }
+
+    fileprivate func loadAccounts() {
+        AppDelegate.accountService.loadAccounts()
+            .subscribe(onSuccess: { (accountList: [AccountModel]) in
+                self.checkAccount(accountList: accountList)
+            }, onError: { _ in
+                self.presentWalkthrough()
+            }).disposed(by: disposeBag)
+    }
+
+    fileprivate func checkAccount(accountList: [AccountModel]) {
+        if accountList.isEmpty {
+            self.presentWalkthrough()
+        } else {
+            self.presentMainTabBar()
+        }
+    }
+
+    fileprivate func presentWalkthrough() {
+        let storyboard = UIStoryboard(name: "WalkthroughStoryboard", bundle: nil)
+        self.window?.rootViewController = storyboard.instantiateInitialViewController()
+        self.window?.makeKeyAndVisible()
+    }
+
+    fileprivate func presentMainTabBar() {
+        let storyboard = UIStoryboard(name: "Main", bundle: nil)
+        self.window?.rootViewController = storyboard.instantiateInitialViewController()
+        self.window?.makeKeyAndVisible()
+    }
 }
diff --git a/Ring/Ring/Constants/Generated/Storyboards.swift b/Ring/Ring/Constants/Generated/Storyboards.swift
index 2e55c0e38..1dedc6f11 100644
--- a/Ring/Ring/Constants/Generated/Storyboards.swift
+++ b/Ring/Ring/Constants/Generated/Storyboards.swift
@@ -45,7 +45,7 @@ enum StoryboardScene {
   enum LaunchScreen: StoryboardSceneType {
     static let storyboardName = "LaunchScreen"
   }
-  enum Main: StoryboardSceneType {
+  enum Main: String, StoryboardSceneType {
     static let storyboardName = "Main"
 
     static func initialViewController() -> Ring.MainTabBarViewController {
@@ -54,6 +54,15 @@ enum StoryboardScene {
       }
       return vc
     }
+
+    case mainStoryboardScene = "MainStoryboard"
+    static func instantiateMainStoryboard() -> Ring.MainTabBarViewController {
+      guard let vc = StoryboardScene.Main.mainStoryboardScene.viewController() as? Ring.MainTabBarViewController
+      else {
+        fatalError("ViewController 'MainStoryboard' is not of the expected class Ring.MainTabBarViewController.")
+      }
+      return vc
+    }
   }
   enum WalkthroughStoryboard: StoryboardSceneType {
     static let storyboardName = "WalkthroughStoryboard"
diff --git a/Ring/Ring/Info.plist b/Ring/Ring/Info.plist
index b4b439184..c2d681014 100644
--- a/Ring/Ring/Info.plist
+++ b/Ring/Ring/Info.plist
@@ -24,8 +24,6 @@
 	<true/>
 	<key>UILaunchStoryboardName</key>
 	<string>LaunchScreen</string>
-	<key>UIMainStoryboardFile</key>
-	<string>Main</string>
 	<key>UIRequiredDeviceCapabilities</key>
 	<array>
 		<string>armv7</string>
diff --git a/Ring/Ring/MainTabBar/MainTabBarViewController.swift b/Ring/Ring/MainTabBar/MainTabBarViewController.swift
index 26be01496..0239ff339 100644
--- a/Ring/Ring/MainTabBar/MainTabBarViewController.swift
+++ b/Ring/Ring/MainTabBar/MainTabBarViewController.swift
@@ -31,14 +31,6 @@ class MainTabBarViewController: UITabBarController {
 
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
-        if !accountService.hasAccounts() {
-            self.presentWalkthrough()
-        }
-    }
 
-    fileprivate func presentWalkthrough() {
-        let storyboard = UIStoryboard(name: "WalkthroughStoryboard", bundle: nil)
-        let viewController = storyboard.instantiateInitialViewController()!
-        self.present(viewController, animated: false, completion: nil)
     }
 }
diff --git a/Ring/Ring/Resources/LaunchScreen.storyboard b/Ring/Ring/Resources/LaunchScreen.storyboard
index 96768f726..2d6fdb214 100644
--- a/Ring/Ring/Resources/LaunchScreen.storyboard
+++ b/Ring/Ring/Resources/LaunchScreen.storyboard
@@ -1,11 +1,11 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11542" systemVersion="15G1108" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+<?xml version="1.0" encoding="UTF-8"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
     <device id="retina4_0" orientation="portrait">
         <adaptation id="fullscreen"/>
     </device>
     <dependencies>
         <deployment identifier="iOS"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11524"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
     <scenes>
diff --git a/Ring/Ring/Resources/Main.storyboard b/Ring/Ring/Resources/Main.storyboard
index 6580f1128..559936750 100644
--- a/Ring/Ring/Resources/Main.storyboard
+++ b/Ring/Ring/Resources/Main.storyboard
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="qdG-Sd-QaE">
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="qdG-Sd-QaE">
     <device id="retina4_0" orientation="portrait">
         <adaptation id="fullscreen"/>
     </device>
@@ -382,7 +382,7 @@
         <!--Ring-->
         <scene sceneID="oqo-zJ-m0o">
             <objects>
-                <tabBarController title="Ring" id="qdG-Sd-QaE" customClass="MainTabBarViewController" customModule="Ring" customModuleProvider="target" sceneMemberID="viewController">
+                <tabBarController storyboardIdentifier="MainStoryboard" title="Ring" id="qdG-Sd-QaE" customClass="MainTabBarViewController" customModule="Ring" customModuleProvider="target" sceneMemberID="viewController">
                     <tabBar key="tabBar" contentMode="scaleToFill" id="zN5-xb-CQh">
                         <rect key="frame" x="0.0" y="0.0" width="320" height="49"/>
                         <autoresizingMask key="autoresizingMask"/>
diff --git a/Ring/Ring/Services/AccountsService.swift b/Ring/Ring/Services/AccountsService.swift
index 1392d97d6..7e8079453 100644
--- a/Ring/Ring/Services/AccountsService.swift
+++ b/Ring/Ring/Services/AccountsService.swift
@@ -131,7 +131,7 @@ class AccountsService: AccountAdapterDelegate {
 
     }
 
-    func loadAccounts() {
+    fileprivate func loadAccountsFromDaemon() {
         for accountId in accountAdapter.getAccountList() {
             if  let id = accountId as? String {
                 self.accountList.append(AccountModel(withAccountId: id))
@@ -141,6 +141,13 @@ class AccountsService: AccountAdapterDelegate {
         reloadAccounts()
     }
 
+    func loadAccounts() -> Single<[AccountModel]> {
+        return Single<[AccountModel]>.just({
+            loadAccountsFromDaemon()
+            return accountList
+        }())
+    }
+
     // MARK: - Methods
     func hasAccounts() -> Bool {
         return !accountList.isEmpty
diff --git a/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift b/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
index 4f60f33ed..a67e13d1f 100644
--- a/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
+++ b/Ring/Ring/Walkthrough/CreateRingAccountViewController.swift
@@ -88,7 +88,10 @@ class CreateRingAccountViewController: UITableViewController {
                 case .success:
                     self.setCreateAccountAsIdle()
                     self.showDeviceAddedAlert()
+                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
+                    let vc = storyboard.instantiateViewController(withIdentifier: "MainStoryboard") as UIViewController
                     self.dismiss(animated: true, completion: nil)
+                    self.present(vc, animated: true, completion: nil)
                 default:
                     return
                 }
-- 
GitLab