ソースを参照

Remove InstanceID from Github repo (#7970)

Chen Liang 5 年 前
コミット
429bac463c
100 ファイル変更2 行追加11053 行削除
  1. 1 3
      .github/workflows/installations.yml
  2. 0 94
      .github/workflows/instanceid.yml
  3. 1 21
      .github/workflows/test_coverage.yml
  4. 0 3
      .gitignore
  5. 0 6
      .travis.yml
  6. 0 1
      CocoapodsIntegrationTest/TestEnvironments/Cocoapods_multiprojects_frameworks/Podfile
  7. 0 1
      CocoapodsIntegrationTest/TestEnvironments/Cocoapods_multiprojects_staticLibs/Podfile
  8. 0 1
      CoreOnly/Tests/FirebasePodTest/Podfile
  9. 0 4
      Dangerfile
  10. 0 30
      Example/InstanceID/App/iOS/Base.lproj/LaunchScreen.storyboard
  11. 0 27
      Example/InstanceID/App/iOS/Base.lproj/Main.storyboard
  12. 0 23
      Example/InstanceID/App/iOS/FIRAppDelegate.h
  13. 0 55
      Example/InstanceID/App/iOS/FIRAppDelegate.m
  14. 0 21
      Example/InstanceID/App/iOS/FIRViewController.h
  15. 0 33
      Example/InstanceID/App/iOS/FIRViewController.m
  16. 0 54
      Example/InstanceID/App/iOS/InstanceID-Info.plist
  17. 0 22
      Example/InstanceID/App/iOS/main.m
  18. 0 21
      Example/InstanceID/App/tvOS/AppDelegate.h
  19. 0 59
      Example/InstanceID/App/tvOS/AppDelegate.m
  20. 0 11
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Back.imagestacklayer/Content.imageset/Contents.json
  21. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Back.imagestacklayer/Contents.json
  22. 0 17
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Contents.json
  23. 0 11
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Front.imagestacklayer/Content.imageset/Contents.json
  24. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Front.imagestacklayer/Contents.json
  25. 0 11
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json
  26. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Middle.imagestacklayer/Contents.json
  27. 0 16
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Back.imagestacklayer/Content.imageset/Contents.json
  28. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Back.imagestacklayer/Contents.json
  29. 0 17
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Contents.json
  30. 0 16
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Front.imagestacklayer/Content.imageset/Contents.json
  31. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Front.imagestacklayer/Contents.json
  32. 0 16
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json
  33. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Middle.imagestacklayer/Contents.json
  34. 0 32
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Contents.json
  35. 0 24
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image Wide.imageset/Contents.json
  36. 0 24
      Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image.imageset/Contents.json
  37. 0 6
      Example/InstanceID/App/tvOS/Assets.xcassets/Contents.json
  38. 0 22
      Example/InstanceID/App/tvOS/Assets.xcassets/Launch Image.launchimage/Contents.json
  39. 0 28
      Example/InstanceID/App/tvOS/Base.lproj/Main.storyboard
  40. 0 32
      Example/InstanceID/App/tvOS/Info.plist
  41. 0 19
      Example/InstanceID/App/tvOS/ViewController.h
  42. 0 28
      Example/InstanceID/App/tvOS/ViewController.m
  43. 0 22
      Example/InstanceID/App/tvOS/main.m
  44. 0 182
      Example/InstanceID/IntegrationTests/FIRInstanceIDIntegrationTests.m
  45. 0 89
      Example/InstanceID/Tests/FIRInstanceIDAPNSInfoTest.m
  46. 0 416
      Example/InstanceID/Tests/FIRInstanceIDAuthKeyChainTest.m
  47. 0 400
      Example/InstanceID/Tests/FIRInstanceIDAuthServiceTest.m
  48. 0 109
      Example/InstanceID/Tests/FIRInstanceIDBackupExcludedPlistTest.m
  49. 0 88
      Example/InstanceID/Tests/FIRInstanceIDCheckinPreferencesTest.m
  50. 0 178
      Example/InstanceID/Tests/FIRInstanceIDCheckinServiceTest.m
  51. 0 225
      Example/InstanceID/Tests/FIRInstanceIDCheckinStoreTest.m
  52. 0 28
      Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h
  53. 0 111
      Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.m
  54. 0 144
      Example/InstanceID/Tests/FIRInstanceIDResultTest.m
  55. 0 242
      Example/InstanceID/Tests/FIRInstanceIDStoreTest.m
  56. 0 1513
      Example/InstanceID/Tests/FIRInstanceIDTest.m
  57. 0 196
      Example/InstanceID/Tests/FIRInstanceIDTokenInfoTest.m
  58. 0 44
      Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.h
  59. 0 50
      Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.m
  60. 0 575
      Example/InstanceID/Tests/FIRInstanceIDTokenManagerTest.m
  61. 0 420
      Example/InstanceID/Tests/FIRInstanceIDTokenOperationsTest.m
  62. 0 95
      Example/InstanceID/Tests/FIRInstanceIDUtilitiesTest.m
  63. 0 22
      Example/InstanceID/Tests/Info.plist
  64. 0 2
      Example/watchOSSample/Podfile
  65. 0 237
      Firebase/InstanceID/CHANGELOG.md
  66. 0 147
      Firebase/InstanceID/FIRIMessageCode.h
  67. 0 52
      Firebase/InstanceID/FIRInstanceID+Private.m
  68. 0 1164
      Firebase/InstanceID/FIRInstanceID.m
  69. 0 64
      Firebase/InstanceID/FIRInstanceIDAPNSInfo.h
  70. 0 79
      Firebase/InstanceID/FIRInstanceIDAPNSInfo.m
  71. 0 96
      Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h
  72. 0 228
      Firebase/InstanceID/FIRInstanceIDAuthKeyChain.m
  73. 0 91
      Firebase/InstanceID/FIRInstanceIDAuthService.h
  74. 0 302
      Firebase/InstanceID/FIRInstanceIDAuthService.m
  75. 0 81
      Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h
  76. 0 117
      Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.m
  77. 0 64
      Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h
  78. 0 112
      Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.m
  79. 0 95
      Firebase/InstanceID/FIRInstanceIDCheckinPreferences.m
  80. 0 27
      Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h
  81. 0 68
      Firebase/InstanceID/FIRInstanceIDCheckinService.h
  82. 0 242
      Firebase/InstanceID/FIRInstanceIDCheckinService.m
  83. 0 96
      Firebase/InstanceID/FIRInstanceIDCheckinStore.h
  84. 0 193
      Firebase/InstanceID/FIRInstanceIDCheckinStore.m
  85. 0 31
      Firebase/InstanceID/FIRInstanceIDCombinedHandler.h
  86. 0 64
      Firebase/InstanceID/FIRInstanceIDCombinedHandler.m
  87. 0 65
      Firebase/InstanceID/FIRInstanceIDConstants.h
  88. 0 47
      Firebase/InstanceID/FIRInstanceIDConstants.m
  89. 0 47
      Firebase/InstanceID/FIRInstanceIDDefines.h
  90. 0 62
      Firebase/InstanceID/FIRInstanceIDKeychain.h
  91. 0 114
      Firebase/InstanceID/FIRInstanceIDKeychain.m
  92. 0 66
      Firebase/InstanceID/FIRInstanceIDLogger.h
  93. 0 92
      Firebase/InstanceID/FIRInstanceIDLogger.m
  94. 0 188
      Firebase/InstanceID/FIRInstanceIDStore.h
  95. 0 243
      Firebase/InstanceID/FIRInstanceIDStore.m
  96. 0 31
      Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.h
  97. 0 119
      Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.m
  98. 0 34
      Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.h
  99. 0 207
      Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.m
  100. 0 92
      Firebase/InstanceID/FIRInstanceIDTokenInfo.h

+ 1 - 3
.github/workflows/installations.yml

@@ -37,8 +37,7 @@ jobs:
       run: |
        export FIS_INTEGRATION_TESTS_REQUIRED=${{ steps.secrets.outputs.val }}
        scripts/third_party/travis/retry.sh scripts/pod_lib_lint.rb FirebaseInstallations.podspec \
-         --platforms=${{ matrix.target }} --ignore-local-podspecs=FirebaseInstanceID.podspec
-
+         --platforms=${{ matrix.target }}
   spm:
     # Don't run on private repo unless it is a PR.
     if: (github.repository == 'Firebase/firebase-ios-sdk' && github.event_name == 'schedule') || github.event_name == 'pull_request'
@@ -126,7 +125,6 @@ jobs:
        export FIS_INTEGRATION_TESTS_REQUIRED=${{ steps.secrets.outputs.val }}
        scripts/third_party/travis/retry.sh scripts/pod_lib_lint.rb FirebaseInstallations.podspec \
          --platforms=${{ matrix.target }} ${{ matrix.flags }} \
-         --ignore-local-podspecs=FirebaseInstanceID.podspec
 
   podspec-presubmit:
     # Don't run on private repo unless it is a PR.

+ 0 - 94
.github/workflows/instanceid.yml

@@ -1,94 +0,0 @@
-name: instanceid
-
-on:
-  pull_request:
-    paths:
-    - 'FirebaseInstanceID**'
-    - 'Firebase/InstanceID/**'
-    - 'Example/InstanceID/**'
-    - '.github/workflows/instanceid.yml'
-    - 'Gemfile*'
-  schedule:
-    # Run every day at 10pm (PST) - cron uses UTC times
-    - cron:  '0 6 * * *'
-
-jobs:
-  pod-lib-lint:
-    # Don't run on private repo unless it is a PR.
-    if: (github.repository == 'Firebase/firebase-ios-sdk' && github.event_name == 'schedule') || github.event_name == 'pull_request'
-    runs-on: macOS-latest
-    env:
-      plist_secret: ${{ secrets.GHASecretsGPGPassphrase1 }}
-    strategy:
-      matrix:
-        target: [ios, tvos, macos]
-    steps:
-    - uses: actions/checkout@v2
-    - name: Setup Bundler
-      run: scripts/setup_bundler.sh
-    - name: Install GoogleService-Info.plist
-      run: |
-        mkdir -p Example/InstanceID/Resources
-        scripts/decrypt_gha_secret.sh scripts/gha-encrypted/Installations/GoogleService-Info.plist.gpg \
-          Example/InstanceID/Resources/GoogleService-Info.plist "$plist_secret"
-    - name: Get boolean for secrets available
-      id: secrets
-      run: echo "::set-output name=val::$([[ -z $plist_secret ]] && echo "0" || echo "1")"
-    - name: Build and test
-      run: |
-       export FIR_IID_INTEGRATION_TESTS_REQUIRED=${{ steps.secrets.outputs.val }}
-       scripts/third_party/travis/retry.sh scripts/pod_lib_lint.rb FirebaseInstanceID.podspec --platforms=${{ matrix.target }}
-
-  catalyst:
-    # Don't run on private repo unless it is a PR.
-    if: (github.repository == 'Firebase/firebase-ios-sdk' && github.event_name == 'schedule') || github.event_name == 'pull_request'
-    runs-on: macOS-latest
-    steps:
-    - uses: actions/checkout@v2
-    - name: Setup Bundler
-      run: scripts/setup_bundler.sh
-    - name: Setup project and Build for Catalyst
-      run: scripts/test_catalyst.sh FirebaseInstanceID test FirebaseInstanceID-Unit-unit
-
-  instanceid-cron-only:
-    # Don't run on private repo.
-    if: github.event_name == 'schedule' && github.repository == 'Firebase/firebase-ios-sdk'
-    runs-on: macos-latest
-    env:
-      plist_secret: ${{ secrets.GHASecretsGPGPassphrase1 }}
-      FIR_IID_INTEGRATION_TESTS_REQUIRED: ${{ secrets.GHASecretsGPGPassphrase1 }}
-    strategy:
-      matrix:
-        target: [ios, tvos, macos]
-        flags: [
-          '--use-static-frameworks',
-          '--use-libraries'
-        ]
-    needs: pod-lib-lint
-    steps:
-    - uses: actions/checkout@v2
-    - name: Setup Bundler
-      run: scripts/setup_bundler.sh
-    - name: Install GoogleService-Info.plist
-      run: |
-        mkdir -p Example/InstanceID/Resources
-        scripts/decrypt_gha_secret.sh scripts/gha-encrypted/Installations/GoogleService-Info.plist.gpg \
-          Example/InstanceID/Resources/GoogleService-Info.plist "$plist_secret"
-    - name: Get boolean for secrets available
-      id: secrets
-      run: echo "::set-output name=val::$([[ -z $plist_secret ]] && echo "0" || echo "1")"
-    - name: PodLibLint InstanceID Cron
-      run: |
-        export FIR_IID_INTEGRATION_TESTS_REQUIRED=${{ steps.secrets.outputs.val }}
-        FIR_IID_INTEGRATION_TESTS_REQUIRED="$plist_secret" scripts/third_party/travis/retry.sh scripts/pod_lib_lint.rb FirebaseInstanceID.podspec --platforms=${{ matrix.target }} ${{ matrix.flags }}
-
-  podspec-presubmit:
-    # Don't run on private repo unless it is a PR.
-    if: github.repository == 'Firebase/firebase-ios-sdk' && github.event.pull_request.merged != true && github.event.action != 'closed'
-    runs-on: macOS-latest
-    steps:
-    - uses: actions/checkout@v2
-    - name: Setup Bundler
-      run: scripts/setup_bundler.sh
-    - name: Build and test
-      run: scripts/third_party/travis/retry.sh pod spec lint FirebaseInstanceID.podspec --skip-tests --sources='https://github.com/firebase/SpecsTesting','https://github.com/firebase/SpecsDev.git','https://github.com/firebase/SpecsStaging.git','https://cdn.cocoapods.org/'

+ 1 - 21
.github/workflows/test_coverage.yml

@@ -22,7 +22,6 @@ jobs:
       firestore_run_job: ${{ steps.check_files.outputs.firestore_run_job }}
       functions_run_job: ${{ steps.check_files.outputs.functions_run_job }}
       inappmessaging_run_job: ${{ steps.check_files.outputs.inappmessaging_run_job }}
-      instanceid_run_job: ${{ steps.check_files.outputs.instanceid_run_job }}
       messaging_run_job: ${{ steps.check_files.outputs.messaging_run_job }}
       performance_run_job: ${{ steps.check_files.outputs.performance_run_job }}
       remoteconfig_run_job: ${{ steps.check_files.outputs.remoteconfig_run_job }}
@@ -178,25 +177,6 @@ jobs:
         name: codecoverage
         path: /Users/runner/*.xcresult
 
-  pod-lib-lint-instanceid:
-    needs: check
-    # Don't run on private repo unless it is a PR.
-    if: always() && github.repository == 'Firebase/firebase-ios-sdk' && (needs.check.outputs.instanceid_run_job == 'true'|| github.event.pull_request.merged)
-    runs-on: macOS-latest
-    strategy:
-      matrix:
-        target: [iOS]
-    steps:
-    - uses: actions/checkout@v2
-    - name: Setup Bundler
-      run: scripts/setup_bundler.sh
-    - name: Build and test
-      run: ./scripts/code_coverage_report/pod_test_code_coverage_report.sh --sdk=FirebaseInstanceID --platform=${{ matrix.target }}
-    - uses: actions/upload-artifact@v2
-      with:
-        name: codecoverage
-        path: /Users/runner/*.xcresult
-
   pod-lib-lint-messaging:
     needs: check
     # Don't run on private repo unless it is a PR.
@@ -274,7 +254,7 @@ jobs:
         path: /Users/runner/*.xcresult
 
   create_report:
-    needs: [check, pod-lib-lint-abtesting, pod-lib-lint-auth, pod-lib-lint-database, pod-lib-lint-dynamiclinks, pod-lib-lint-firestore, pod-lib-lint-functions, pod-lib-lint-inappmessaging, pod-lib-lint-instanceid, pod-lib-lint-messaging, pod-lib-lint-performance, pod-lib-lint-remoteconfig, pod-lib-lint-storage]
+    needs: [check, pod-lib-lint-abtesting, pod-lib-lint-auth, pod-lib-lint-database, pod-lib-lint-dynamiclinks, pod-lib-lint-firestore, pod-lib-lint-functions, pod-lib-lint-inappmessaging, pod-lib-lint-messaging, pod-lib-lint-performance, pod-lib-lint-remoteconfig, pod-lib-lint-storage]
     if: always()
     runs-on: macOS-latest
     steps:

+ 0 - 3
.gitignore

@@ -18,9 +18,6 @@ FirebaseStorage/Tests/Integration/Resources/GoogleService-Info.plist
 # FirebaseInstallations integration tests GoogleService-Info.plist
 FirebaseInstallations/Source/Tests/Resources/GoogleService-Info.plist
 
-# FirebaseInstanceID integration tests GoogleService-Info.plist
-Example/InstanceID/Resources/GoogleService-Info.plist
-
 # FirebaseMessaging integration tests GoogleService-Info.plist
 FirebaseMessaging/Tests/IntegrationTests/Resources/GoogleService-Info.plist
 # FirebaseMessaging test app GoogleService-Info.plist

+ 0 - 6
.travis.yml

@@ -55,12 +55,6 @@ jobs:
       script:
         - travis_retry ./scripts/if_changed.sh ./scripts/pod_lib_lint.rb FirebaseAuth.podspec --platforms=ios
 
-    - stage: test
-      env:
-        - PROJECT=InstanceID METHOD=pod-lib-lint
-      script:
-        - travis_retry ./scripts/if_changed.sh ./scripts/pod_lib_lint.rb FirebaseInstanceID.podspec --platforms=ios
-
     - stage: test
       env:
         - PROJECT=Database PLATFORM=all METHOD=xcodebuild

+ 0 - 1
CocoapodsIntegrationTest/TestEnvironments/Cocoapods_multiprojects_frameworks/Podfile

@@ -20,7 +20,6 @@ target 'CocoapodsIntegrationTest' do
   pod 'FirebaseFunctions', :path => '../'
   pod 'FirebaseInAppMessaging', :path => '../'
   pod 'FirebaseInstallations', :path => '../'
-  pod 'FirebaseInstanceID', :path => '../'
   pod 'FirebaseMessaging', :path => '../'
   pod 'FirebasePerformance', :path => '../'
   pod 'FirebaseStorage', :path => '../'

+ 0 - 1
CocoapodsIntegrationTest/TestEnvironments/Cocoapods_multiprojects_staticLibs/Podfile

@@ -18,7 +18,6 @@ target 'CocoapodsIntegrationTest' do
   pod 'FirebaseFunctions', :path => '../'
   pod 'FirebaseInAppMessaging', :path => '../'
   pod 'FirebaseInstallations', :path => '../'
-  pod 'FirebaseInstanceID', :path => '../'
   pod 'FirebaseMessaging', :path => '../'
   pod 'FirebasePerformance', :path => '../'
   pod 'FirebaseStorage', :path => '../'

+ 0 - 1
CoreOnly/Tests/FirebasePodTest/Podfile

@@ -25,7 +25,6 @@ target 'FirebasePodTest' do
   pod 'FirebaseInAppMessaging', :path => '../../../'
   pod 'FirebaseInAppMessagingSwift', :path => '../../../'
   pod 'FirebaseInstallations', :path => '../../../'
-  pod 'FirebaseInstanceID', :path => '../../../'
   pod 'FirebaseMessaging', :path => '../../../'
   pod 'FirebasePerformance', :path => '../../../'
   pod 'FirebaseRemoteConfig', :path => '../../../'

+ 0 - 4
Dangerfile

@@ -47,7 +47,6 @@ def labelsForModifiedFiles()
   labels.push("api: functions") if @has_functions_changes
   labels.push("api: inappmessaging") if @has_inappmessaging_changes
   labels.push("api: installations") if @has_installations_changes
-  labels.push("api: instanceid") if @has_instanceid_changes
   labels.push("api: messaging") if @has_messaging_changes
   labels.push("api: performance") if @has_performance_changes
   labels.push("api: remoteconfig") if @has_remoteconfig_changes
@@ -99,8 +98,6 @@ has_license_changes = didModify(["LICENSE"])
 @has_inappmessaging_api_changes = hasChangesIn(["FirebaseInAppMessaging/Sources/Public/"])
 @has_installations_changes = hasChangesIn("FirebaseInstallations")
 @has_installations_api_changes = hasChangesIn("FirebaseInstallations/Source/Library/Public/")
-@has_instanceid_changes = hasChangesIn("Firebase/InstanceID/")
-@has_instanceid_api_changes = hasChangesIn("Firebase/InstanceID/Public/")
 @has_messaging_changes = hasChangesIn("FirebaseMessaging")
 @has_messaging_api_changes = hasChangesIn("FirebaseMessaging/Sources/Public/")
 @has_performance_changes = hasChangesIn("FirebasePerformance")
@@ -127,7 +124,6 @@ has_license_changes = didModify(["LICENSE"])
                      @has_functions_api_changes ||
                      @has_inappmessaging_api_changes ||
                      @has_installations_api_changes ||
-                     @has_instanceid_api_changes ||
                      @has_messaging_api_changes ||
                      @has_performance_api_changes ||
                      @has_remoteconfig_api_changes ||

+ 0 - 30
Example/InstanceID/App/iOS/Base.lproj/LaunchScreen.storyboard

@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
-    <device id="retina4_7" orientation="portrait">
-        <adaptation id="fullscreen"/>
-    </device>
-    <dependencies>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
-        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
-    </dependencies>
-    <scenes>
-        <!--View Controller-->
-        <scene sceneID="EHf-IW-A2E">
-            <objects>
-                <viewController id="01J-lp-oVM" sceneMemberID="viewController">
-                    <layoutGuides>
-                        <viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
-                        <viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
-                    </layoutGuides>
-                    <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
-                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
-                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
-                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
-                    </view>
-                </viewController>
-                <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
-            </objects>
-            <point key="canvasLocation" x="53" y="375"/>
-        </scene>
-    </scenes>
-</document>

+ 0 - 27
Example/InstanceID/App/iOS/Base.lproj/Main.storyboard

@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7706" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="whP-gf-Uak">
-    <dependencies>
-        <deployment identifier="iOS"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
-    </dependencies>
-    <scenes>
-        <!--View Controller-->
-        <scene sceneID="wQg-tq-qST">
-            <objects>
-                <viewController id="whP-gf-Uak" customClass="FIRViewController" sceneMemberID="viewController">
-                    <layoutGuides>
-                        <viewControllerLayoutGuide type="top" id="uEw-UM-LJ8"/>
-                        <viewControllerLayoutGuide type="bottom" id="Mvr-aV-6Um"/>
-                    </layoutGuides>
-                    <view key="view" contentMode="scaleToFill" id="TpU-gO-2f1">
-                        <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
-                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
-                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
-                    </view>
-                </viewController>
-                <placeholder placeholderIdentifier="IBFirstResponder" id="tc2-Qw-aMS" userLabel="First Responder" sceneMemberID="firstResponder"/>
-            </objects>
-            <point key="canvasLocation" x="305" y="433"/>
-        </scene>
-    </scenes>
-</document>

+ 0 - 23
Example/InstanceID/App/iOS/FIRAppDelegate.h

@@ -1,23 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-@import UIKit;
-
-@interface FIRAppDelegate : UIResponder <UIApplicationDelegate>
-
-@property(strong, nonatomic) UIWindow *window;
-
-@end

+ 0 - 55
Example/InstanceID/App/iOS/FIRAppDelegate.m

@@ -1,55 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "FIRAppDelegate.h"
-
-@implementation FIRAppDelegate
-
-- (BOOL)application:(UIApplication *)application
-    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
-  return YES;
-}
-
-- (void)applicationWillResignActive:(UIApplication *)application {
-  // 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.
-  // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame
-  // rates. Games should use this method to pause the game.
-}
-
-- (void)applicationDidEnterBackground:(UIApplication *)application {
-  // 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.
-  // If your application supports background execution, this method is called instead of
-  // applicationWillTerminate: when the user quits.
-}
-
-- (void)applicationWillEnterForeground:(UIApplication *)application {
-  // Called as part of the transition from the background to the inactive state; here you can undo
-  // many of the changes made on entering the background.
-}
-
-- (void)applicationDidBecomeActive:(UIApplication *)application {
-  // 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.
-}
-
-- (void)applicationWillTerminate:(UIApplication *)application {
-  // Called when the application is about to terminate. Save data if appropriate. See also
-  // applicationDidEnterBackground:.
-}
-
-@end

+ 0 - 21
Example/InstanceID/App/iOS/FIRViewController.h

@@ -1,21 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-@import UIKit;
-
-@interface FIRViewController : UIViewController
-
-@end

+ 0 - 33
Example/InstanceID/App/iOS/FIRViewController.m

@@ -1,33 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "FIRViewController.h"
-
-@interface FIRViewController ()
-
-@end
-
-@implementation FIRViewController
-
-- (void)viewDidLoad {
-  [super viewDidLoad];
-  // Do any additional setup after loading the view, typically from a nib.
-}
-
-- (void)didReceiveMemoryWarning {
-  [super didReceiveMemoryWarning];
-  // Dispose of any resources that can be recreated.
-}
-
-@end

+ 0 - 54
Example/InstanceID/App/iOS/InstanceID-Info.plist

@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-	<key>CFBundleDevelopmentRegion</key>
-	<string>en</string>
-	<key>CFBundleDisplayName</key>
-	<string>${PRODUCT_NAME}</string>
-	<key>CFBundleExecutable</key>
-	<string>${EXECUTABLE_NAME}</string>
-	<key>CFBundleIdentifier</key>
-	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>${PRODUCT_NAME}</string>
-	<key>CFBundlePackageType</key>
-	<string>APPL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>1.0</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>1.0</string>
-	<key>LSRequiresIPhoneOS</key>
-	<true/>
-	<key>NSAppTransportSecurity</key>
-	<dict>
-		<key>NSAllowsArbitraryLoads</key>
-		<true/>
-	</dict>
-	<key>UILaunchStoryboardName</key>
-	<string>LaunchScreen</string>
-	<key>UIMainStoryboardFile</key>
-	<string>Main</string>
-	<key>UIRequiredDeviceCapabilities</key>
-	<array>
-		<string>armv7</string>
-	</array>
-	<key>UISupportedInterfaceOrientations</key>
-	<array>
-		<string>UIInterfaceOrientationPortrait</string>
-		<string>UIInterfaceOrientationLandscapeLeft</string>
-		<string>UIInterfaceOrientationLandscapeRight</string>
-	</array>
-	<key>UISupportedInterfaceOrientations~ipad</key>
-	<array>
-		<string>UIInterfaceOrientationPortrait</string>
-		<string>UIInterfaceOrientationPortraitUpsideDown</string>
-		<string>UIInterfaceOrientationLandscapeLeft</string>
-		<string>UIInterfaceOrientationLandscapeRight</string>
-	</array>
-</dict>
-</plist>

+ 0 - 22
Example/InstanceID/App/iOS/main.m

@@ -1,22 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-@import UIKit;
-#import "FIRAppDelegate.h"
-
-int main(int argc, char* argv[]) {
-  @autoreleasepool {
-    return UIApplicationMain(argc, argv, nil, NSStringFromClass([FIRAppDelegate class]));
-  }
-}

+ 0 - 21
Example/InstanceID/App/tvOS/AppDelegate.h

@@ -1,21 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import <UIKit/UIKit.h>
-
-@interface AppDelegate : UIResponder <UIApplicationDelegate>
-
-@property(strong, nonatomic) UIWindow *window;
-
-@end

+ 0 - 59
Example/InstanceID/App/tvOS/AppDelegate.m

@@ -1,59 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "AppDelegate.h"
-
-@interface AppDelegate ()
-
-@end
-
-@implementation AppDelegate
-
-- (BOOL)application:(UIApplication *)application
-    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
-  // Override point for customization after application launch.
-  return YES;
-}
-
-- (void)applicationWillResignActive:(UIApplication *)application {
-  // 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. Use
-  // this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates.
-  // Games should use this method to pause the game.
-}
-
-- (void)applicationDidEnterBackground:(UIApplication *)application {
-  // 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. If your application supports background execution, this method is
-  // called instead of applicationWillTerminate: when the user quits.
-}
-
-- (void)applicationWillEnterForeground:(UIApplication *)application {
-  // 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.
-}
-
-- (void)applicationDidBecomeActive:(UIApplication *)application {
-  // 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.
-}
-
-- (void)applicationWillTerminate:(UIApplication *)application {
-  // Called when the application is about to terminate. Save data if appropriate. See also
-  // applicationDidEnterBackground:.
-}
-
-@end

+ 0 - 11
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Back.imagestacklayer/Content.imageset/Contents.json

@@ -1,11 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Back.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 17
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Contents.json

@@ -1,17 +0,0 @@
-{
-  "layers" : [
-    {
-      "filename" : "Front.imagestacklayer"
-    },
-    {
-      "filename" : "Middle.imagestacklayer"
-    },
-    {
-      "filename" : "Back.imagestacklayer"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 11
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Front.imagestacklayer/Content.imageset/Contents.json

@@ -1,11 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Front.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 11
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json

@@ -1,11 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - App Store.imagestack/Middle.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 16
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Back.imagestacklayer/Content.imageset/Contents.json

@@ -1,16 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv",
-      "scale" : "2x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Back.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 17
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Contents.json

@@ -1,17 +0,0 @@
-{
-  "layers" : [
-    {
-      "filename" : "Front.imagestacklayer"
-    },
-    {
-      "filename" : "Middle.imagestacklayer"
-    },
-    {
-      "filename" : "Back.imagestacklayer"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 16
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Front.imagestacklayer/Content.imageset/Contents.json

@@ -1,16 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv",
-      "scale" : "2x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Front.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 16
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json

@@ -1,16 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv",
-      "scale" : "2x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon.imagestack/Middle.imagestacklayer/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 32
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Contents.json

@@ -1,32 +0,0 @@
-{
-  "assets" : [
-    {
-      "size" : "1280x768",
-      "idiom" : "tv",
-      "filename" : "App Icon - App Store.imagestack",
-      "role" : "primary-app-icon"
-    },
-    {
-      "size" : "400x240",
-      "idiom" : "tv",
-      "filename" : "App Icon.imagestack",
-      "role" : "primary-app-icon"
-    },
-    {
-      "size" : "2320x720",
-      "idiom" : "tv",
-      "filename" : "Top Shelf Image Wide.imageset",
-      "role" : "top-shelf-image-wide"
-    },
-    {
-      "size" : "1920x720",
-      "idiom" : "tv",
-      "filename" : "Top Shelf Image.imageset",
-      "role" : "top-shelf-image"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 24
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image Wide.imageset/Contents.json

@@ -1,24 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv",
-      "scale" : "2x"
-    },
-    {
-      "idiom" : "tv-marketing",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv-marketing",
-      "scale" : "2x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 24
Example/InstanceID/App/tvOS/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image.imageset/Contents.json

@@ -1,24 +0,0 @@
-{
-  "images" : [
-    {
-      "idiom" : "tv",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv",
-      "scale" : "2x"
-    },
-    {
-      "idiom" : "tv-marketing",
-      "scale" : "1x"
-    },
-    {
-      "idiom" : "tv-marketing",
-      "scale" : "2x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 6
Example/InstanceID/App/tvOS/Assets.xcassets/Contents.json

@@ -1,6 +0,0 @@
-{
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 22
Example/InstanceID/App/tvOS/Assets.xcassets/Launch Image.launchimage/Contents.json

@@ -1,22 +0,0 @@
-{
-  "images" : [
-    {
-      "orientation" : "landscape",
-      "idiom" : "tv",
-      "extent" : "full-screen",
-      "minimum-system-version" : "11.0",
-      "scale" : "2x"
-    },
-    {
-      "orientation" : "landscape",
-      "idiom" : "tv",
-      "extent" : "full-screen",
-      "minimum-system-version" : "9.0",
-      "scale" : "1x"
-    }
-  ],
-  "info" : {
-    "version" : 1,
-    "author" : "xcode"
-  }
-}

+ 0 - 28
Example/InstanceID/App/tvOS/Base.lproj/Main.storyboard

@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder.AppleTV.Storyboard" version="3.0" toolsVersion="13122.16" targetRuntime="AppleTV" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
-    <dependencies>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
-        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
-        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
-    </dependencies>
-    <scenes>
-        <!--View Controller-->
-        <scene sceneID="tne-QT-ifu">
-            <objects>
-                <viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="" sceneMemberID="viewController">
-                    <layoutGuides>
-                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
-                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
-                    </layoutGuides>
-                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
-                        <rect key="frame" x="0.0" y="0.0" width="1920" height="1080"/>
-                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
-                        <color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/>
-                        <viewLayoutGuide key="safeArea" id="wu6-TO-1qx"/>
-                    </view>
-                </viewController>
-                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
-            </objects>
-        </scene>
-    </scenes>
-</document>

+ 0 - 32
Example/InstanceID/App/tvOS/Info.plist

@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-	<key>CFBundleDevelopmentRegion</key>
-	<string>$(DEVELOPMENT_LANGUAGE)</string>
-	<key>CFBundleExecutable</key>
-	<string>$(EXECUTABLE_NAME)</string>
-	<key>CFBundleIdentifier</key>
-	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>$(PRODUCT_NAME)</string>
-	<key>CFBundlePackageType</key>
-	<string>APPL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>1.0</string>
-	<key>CFBundleVersion</key>
-	<string>1</string>
-	<key>LSRequiresIPhoneOS</key>
-	<true/>
-	<key>UIMainStoryboardFile</key>
-	<string>Main</string>
-	<key>UIRequiredDeviceCapabilities</key>
-	<array>
-		<string>arm64</string>
-	</array>
-	<key>UIUserInterfaceStyle</key>
-	<string>Automatic</string>
-</dict>
-</plist>

+ 0 - 19
Example/InstanceID/App/tvOS/ViewController.h

@@ -1,19 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import <UIKit/UIKit.h>
-
-@interface ViewController : UIViewController
-
-@end

+ 0 - 28
Example/InstanceID/App/tvOS/ViewController.m

@@ -1,28 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "ViewController.h"
-
-@interface ViewController ()
-
-@end
-
-@implementation ViewController
-
-- (void)viewDidLoad {
-  [super viewDidLoad];
-  // Do any additional setup after loading the view, typically from a nib.
-}
-
-@end

+ 0 - 22
Example/InstanceID/App/tvOS/main.m

@@ -1,22 +0,0 @@
-// Copyright 2019 Google
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import <UIKit/UIKit.h>
-#import "AppDelegate.h"
-
-int main(int argc, char* argv[]) {
-  @autoreleasepool {
-    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
-  }
-}

+ 0 - 182
Example/InstanceID/IntegrationTests/FIRInstanceIDIntegrationTests.m

@@ -1,182 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// macOS requests a user password when accessing the Keychain for the first time,
-// so the tests may fail. Disable integration tests on macOS so far.
-// TODO: Configure the tests to run on macOS without requesting the keychain password.
-#if !TARGET_OS_OSX
-
-#import <XCTest/XCTest.h>
-
-#import <FirebaseCore/FirebaseCore.h>
-#import "Firebase/InstanceID/Public/FirebaseInstanceID.h"
-
-static BOOL sFIRInstanceIDFirebaseDefaultAppConfigured = NO;
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-@interface FIRInstanceIDIntegrationTests : XCTestCase
-@property(nonatomic, strong) FIRInstanceID *instanceID;
-@end
-
-@implementation FIRInstanceIDIntegrationTests
-
-- (void)setUp {
-  [self configureFirebaseDefaultAppIfCan];
-
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  self.instanceID = [FIRInstanceID instanceID];
-}
-
-- (void)tearDown {
-  self.instanceID = nil;
-}
-
-- (void)testGetID {
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  XCTestExpectation *expectation = [self expectationWithDescription:@"getID"];
-  [self.instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
-    XCTAssertNil(error);
-    XCTAssertEqual(identity.length, 22);
-    [expectation fulfill];
-  }];
-  [self waitForExpectations:@[ expectation ] timeout:5];
-}
-
-- (void)testInstanceIDWithHandler {
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  XCTestExpectation *expectation = [self expectationWithDescription:@"instanceIDWithHandler"];
-  [self.instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        XCTAssertNil(error);
-        XCTAssertNotNil(result);
-        XCTAssert(result.instanceID.length > 0);
-        XCTAssert(result.token.length > 0);
-        [expectation fulfill];
-      }];
-
-  [self waitForExpectations:@[ expectation ] timeout:5];
-}
-
-- (void)testTokenWithAuthorizedEntity {
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  [self assertTokenWithAuthorizedEntity];
-}
-
-- (void)testDeleteToken {
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  [self assertTokenWithAuthorizedEntity];
-
-  XCTestExpectation *expectation = [self expectationWithDescription:@"testDeleteToken"];
-  [self.instanceID deleteTokenWithAuthorizedEntity:[self tokenAuthorizedEntity]
-                                             scope:@"*"
-                                           handler:^(NSError *_Nonnull error) {
-                                             XCTAssertNil(error);
-                                             [expectation fulfill];
-                                           }];
-
-  [self waitForExpectations:@[ expectation ] timeout:5];
-}
-
-- (void)testDeleteID {
-  if (![self isDefaultAppConfigured]) {
-    return;
-  }
-
-  XCTestExpectation *expectation = [self expectationWithDescription:@"deleteID"];
-  [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
-    XCTAssertNil(error);
-    [expectation fulfill];
-  }];
-
-  [self waitForExpectations:@[ expectation ] timeout:5];
-}
-
-#pragma mark - Helpers
-
-- (void)assertTokenWithAuthorizedEntity {
-  XCTestExpectation *expectation = [self expectationWithDescription:@"tokenWithAuthorizedEntity"];
-  [self.instanceID
-      tokenWithAuthorizedEntity:[self tokenAuthorizedEntity]
-                          scope:@"*"
-                        options:nil
-                        handler:^(NSString *_Nullable token, NSError *_Nullable error) {
-                          XCTAssertNil(error);
-                          XCTAssert(token > 0);
-                          [expectation fulfill];
-                        }];
-
-  [self waitForExpectations:@[ expectation ] timeout:5];
-}
-#pragma clang diagnostic pop
-
-- (NSString *)tokenAuthorizedEntity {
-  if (!sFIRInstanceIDFirebaseDefaultAppConfigured) {
-    return @"";
-  }
-
-  return [FIRApp defaultApp].options.GCMSenderID;
-}
-
-- (void)configureFirebaseDefaultAppIfCan {
-  if (sFIRInstanceIDFirebaseDefaultAppConfigured) {
-    return;
-  }
-
-  NSBundle *bundle = [NSBundle bundleForClass:[self class]];
-  NSString *plistPath = [bundle pathForResource:@"GoogleService-Info" ofType:@"plist"];
-  if (plistPath == nil) {
-    return;
-  }
-
-  FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:plistPath];
-  [FIRApp configureWithOptions:options];
-  sFIRInstanceIDFirebaseDefaultAppConfigured = YES;
-}
-
-- (BOOL)isDefaultAppConfigured {
-  if (!sFIRInstanceIDFirebaseDefaultAppConfigured) {
-// Fail tests requiring GoogleService-Info.plist only if it is required.
-#if FIR_IID_INTEGRATION_TESTS_REQUIRED
-    XCTFail(@"GoogleService-Info.plist for integration tests was not found. Please add the file to "
-            @"your project.");
-#else
-    NSLog(@"GoogleService-Info.plist for integration tests was not found. Skipping the test %@",
-          self.name);
-#endif  // FIR_IID_INTEGRATION_TESTS_REQUIRED
-  }
-
-  return sFIRInstanceIDFirebaseDefaultAppConfigured;
-}
-
-@end
-
-#endif  // !TARGET_OS_OSX

+ 0 - 89
Example/InstanceID/Tests/FIRInstanceIDAPNSInfoTest.m

@@ -1,89 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDAPNSInfo.h"
-
-#import <XCTest/XCTest.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-
-@interface FIRInstanceIDAPNSInfoTest : XCTestCase
-
-@end
-
-@implementation FIRInstanceIDAPNSInfoTest
-
-- (void)testAPNSInfoCreationWithValidDictionary {
-  NSDictionary *validDictionary = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [@"tokenData" dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES)
-  };
-  FIRInstanceIDAPNSInfo *info =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:validDictionary];
-  XCTAssertNotNil(info);
-  XCTAssertEqualObjects(info.deviceToken, validDictionary[kFIRInstanceIDTokenOptionsAPNSKey]);
-  XCTAssertEqual(info.sandbox,
-                 [validDictionary[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue]);
-}
-
-- (void)testAPNSInfoCreationWithInvalidDictionary {
-  NSDictionary *validDictionary = @{};
-  FIRInstanceIDAPNSInfo *info =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:validDictionary];
-  XCTAssertNil(info);
-}
-
-- (void)testAPNSInfoCreationWithInvalidTokenFormat {
-  // Token data stored as NSString instead of NSData
-  NSDictionary *badDictionary = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : @"tokenDataAsString",
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES)
-  };
-  FIRInstanceIDAPNSInfo *info =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:badDictionary];
-  XCTAssertNil(info);
-}
-
-- (void)testAPNSInfoCreationWithInvalidSandboxFormat {
-  // Sandbox key stored as NSString instead of NSNumber (bool)
-  NSDictionary *validDictionary = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [@"tokenData" dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @"sandboxValueAsString"
-  };
-  FIRInstanceIDAPNSInfo *info =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:validDictionary];
-  XCTAssertNil(info);
-}
-
-// Test that archiving a FIRInstanceIDAPNSInfo object and restoring it from the archive
-// yields the same values for all the fields.
-- (void)testAPNSInfoEncodingAndDecoding {
-  NSDictionary *validDictionary = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [@"tokenData" dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @"sandboxValueAsString"
-  };
-  FIRInstanceIDAPNSInfo *info =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:validDictionary];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:info];
-  FIRInstanceIDAPNSInfo *restoredInfo = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
-#pragma clang diagnostic pop
-  XCTAssertEqualObjects(info.deviceToken, restoredInfo.deviceToken);
-  XCTAssertEqual(info.sandbox, restoredInfo.sandbox);
-}
-
-@end

+ 0 - 416
Example/InstanceID/Tests/FIRInstanceIDAuthKeyChainTest.m

@@ -1,416 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <TargetConditionals.h>
-#if !TARGET_OS_MACCATALYST
-// Skip keychain tests on Catalyst.
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-
-static NSString *const kFIRInstanceIDTestKeychainId = @"com.google.iid-tests";
-
-static NSString *const kAuthorizedEntity = @"test-audience";
-static NSString *const kScope = @"test-scope";
-
-static NSString *const kToken1 =
-    @"dOr37DpYQ9M:APA91bE5aQ2expDEmoSNDDrZqS6drAz2V-GHJHEsa-qVdlHXVSlWpUsK-Ta6Oe1QsVSLovL7_"
-    @"rbm8GNnP7XPfwjtDQrjxYS1BdtxHdVVnQKuxlF3Z0QOwL380l1e1Fz91PX5b77XKj0FIyqzX1z0uJc0-pM6YcaPGg";
-#if TARGET_OS_IOS || TARGET_OS_TV
-static NSString *const kAuthID = @"test-auth-id";
-static NSString *const kSecret = @"test-secret";
-static NSString *const kToken2 = @"c8oEXUYIl3s:APA91bHtJMs_dZ2lXYXIcwsC47abYIuWhEJ_CshY2PJRjVuI_"
-                                 @"H659iYUwfmNNghnZVkCmeUdKDSrK8xqVb0PVHxyAW391Ynp2NchMB87kJWb3BS0z"
-                                 @"ud6Ej_xDES_oc353eFRvt0E6NXefDmrUCpBY8y89_1eVFFfiA";
-#endif
-static NSString *const kFirebaseAppID = @"abcdefg:ios:QrjxYS1BdtxHdVVnQKuxlF3Z0QO";
-
-static NSString *const kBundleID1 = @"com.google.fcm.dev";
-static NSString *const kBundleID2 = @"com.google.abtesting.dev";
-
-@interface FIRInstanceIDAuthKeychain (ExposedForTest)
-
-@property(nonatomic, copy)
-    NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSArray<NSData *> *> *>
-        *cachedKeychainData;
-- (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account;
-
-@end
-
-@interface FIRInstanceIDAuthKeyChainTest : XCTestCase
-
-@end
-
-@implementation FIRInstanceIDAuthKeyChainTest
-
-- (void)setUp {
-  [super setUp];
-}
-
-- (void)tearDown {
-  [super tearDown];
-}
-
-- (void)testKeyChainNoCorruptionWithUniqueAccount {
-// macOS only support one service and one account.
-#if TARGET_OS_IOS || TARGET_OS_TV
-  XCTestExpectation *noCurruptionExpectation =
-      [self expectationWithDescription:@"No corruption between different accounts."];
-  // Create a keychain with a service and a unique account
-  NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-  NSString *account1 = kBundleID1;
-  NSData *tokenInfoData1 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken1];
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-  __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
-  [keychain setData:tokenInfoData1
-         forService:service
-            account:account1
-            handler:^(NSError *error) {
-              XCTAssertNil(error);
-              // Create another keychain with the same service but different account.
-              NSString *account2 = kBundleID2;
-              NSData *tokenInfoData2 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                                     scope:kScope
-                                                                     token:kToken2];
-              [weakKeychain
-                     setData:tokenInfoData2
-                  forService:service
-                     account:account2
-                     handler:^(NSError *error) {
-                       XCTAssertNil(error);
-                       // Now query the token and compare, they should not corrupt
-                       // each other.
-                       NSData *data1 = [weakKeychain dataForService:service account:account1];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-                       FIRInstanceIDTokenInfo *tokenInfo1 =
-                           [NSKeyedUnarchiver unarchiveObjectWithData:data1];
-                       XCTAssertEqualObjects(kToken1, tokenInfo1.token);
-
-                       NSData *data2 = [weakKeychain dataForService:service account:account2];
-                       FIRInstanceIDTokenInfo *tokenInfo2 =
-                           [NSKeyedUnarchiver unarchiveObjectWithData:data2];
-#pragma clang diagnostic pop
-                       XCTAssertEqualObjects(kToken2, tokenInfo2.token);
-                       // Also check the cache data.
-                       XCTAssertEqual(weakKeychain.cachedKeychainData.count, 1);
-                       XCTAssertEqual(weakKeychain.cachedKeychainData[service].count, 2);
-                       XCTAssertEqualObjects(
-                           weakKeychain.cachedKeychainData[service][account1].firstObject,
-                           tokenInfoData1);
-                       XCTAssertEqualObjects(
-                           weakKeychain.cachedKeychainData[service][account2].firstObject,
-                           tokenInfoData2);
-
-                       // Check wildcard query
-                       NSArray *results = [weakKeychain itemsMatchingService:service account:@"*"];
-                       XCTAssertEqual(results.count, 2);
-
-                       // Clean up keychain at the end
-                       [weakKeychain removeItemsMatchingService:service
-                                                        account:@"*"
-                                                        handler:^(NSError *_Nonnull error) {
-                                                          XCTAssertNil(error);
-                                                          [noCurruptionExpectation fulfill];
-                                                        }];
-                     }];
-            }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-#endif
-}
-
-- (void)testKeyChainNoCorruptionWithUniqueService {
-#if TARGET_OS_IOS || TARGET_OS_TV
-  XCTestExpectation *noCurruptionExpectation =
-      [self expectationWithDescription:@"No corruption between different services."];
-  // Create a keychain with a service and a unique account
-  NSString *service1 = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-  NSString *account = kBundleID1;
-  NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                    scope:kScope
-                                                    token:kToken1];
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-  __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
-  [keychain
-         setData:tokenData
-      forService:service1
-         account:account
-         handler:^(NSError *error) {
-           XCTAssertNil(error);
-           // Store a checkin info using the same keychain account, but different service.
-           NSString *service2 = @"com.google.iid.checkin";
-           FIRInstanceIDCheckinPreferences *preferences =
-               [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID
-                                                             secretToken:kSecret];
-           NSString *checkinKeychainContent = [preferences checkinKeychainContent];
-           NSData *checkinData = [checkinKeychainContent dataUsingEncoding:NSUTF8StringEncoding];
-
-           [weakKeychain
-                  setData:checkinData
-               forService:service2
-                  account:account
-                  handler:^(NSError *error) {
-                    XCTAssertNil(error);
-                    // Now query the token and compare, they should not corrupt
-                    // each other.
-                    NSData *data1 = [weakKeychain dataForService:service1 account:account];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-                    FIRInstanceIDTokenInfo *tokenInfo1 =
-                        [NSKeyedUnarchiver unarchiveObjectWithData:data1];
-#pragma clang diagnostic pop
-                    XCTAssertEqualObjects(kToken1, tokenInfo1.token);
-
-                    NSData *data2 = [weakKeychain dataForService:service2 account:account];
-                    NSString *checkinKeychainContent =
-                        [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
-                    FIRInstanceIDCheckinPreferences *checkinPreferences =
-                        [FIRInstanceIDCheckinPreferences
-                            preferencesFromKeychainContents:checkinKeychainContent];
-                    XCTAssertEqualObjects(checkinPreferences.secretToken, kSecret);
-                    XCTAssertEqualObjects(checkinPreferences.deviceID, kAuthID);
-
-                    NSArray *results = [weakKeychain itemsMatchingService:@"*" account:account];
-                    XCTAssertEqual(results.count, 2);
-                    // Also check the cache data.
-                    XCTAssertEqual(weakKeychain.cachedKeychainData.count, 2);
-                    XCTAssertEqualObjects(
-                        weakKeychain.cachedKeychainData[service1][account].firstObject, tokenData);
-                    XCTAssertEqualObjects(
-                        weakKeychain.cachedKeychainData[service2][account].firstObject,
-                        checkinData);
-
-                    // Clean up keychain at the end
-                    [weakKeychain removeItemsMatchingService:@"*"
-                                                     account:@"*"
-                                                     handler:^(NSError *_Nonnull error) {
-                                                       XCTAssertNil(error);
-                                                       [noCurruptionExpectation fulfill];
-                                                     }];
-                  }];
-         }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-#endif
-}
-
-- (void)testQueryCachedKeychainItems {
-  XCTestExpectation *addItemToKeychainExpectation =
-      [self expectationWithDescription:@"Test added item should be cached properly"];
-  // A wildcard query should return empty data when there's nothing in keychain
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-  id keychainMock = OCMPartialMock(keychain);
-
-  NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
-  XCTAssertEqual(result.count, 0);
-
-  // Create a keychain item
-  NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-  NSString *account = kBundleID1;
-  NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                    scope:kScope
-                                                    token:kToken1];
-  __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
-  __weak id weakKeychainMock = keychainMock;
-  [keychain setData:tokenData
-         forService:service
-            account:account
-            handler:^(NSError *error) {
-              XCTAssertNil(error);
-
-              // Now if we clean the cache
-              [weakKeychain.cachedKeychainData removeAllObjects];
-              // Then query the item should fetch from keychain.
-              NSData *data = [weakKeychain dataForService:service account:account];
-              XCTAssertEqualObjects(data, tokenData);
-              // Verify we fetch from keychain by calling to get the query
-              OCMVerify([weakKeychainMock keychainQueryForService:service account:account]);
-              // Cache should now have the query item
-              XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
-                                    tokenData);
-              // Wildcard query should simply return the results without cache it
-              data = [weakKeychain dataForService:@"*" account:account];
-              XCTAssertEqualObjects(data, tokenData);
-              // Cache should not have wildcard query entry
-              XCTAssertNil(weakKeychain.cachedKeychainData[@"*"]);
-
-              // Assume keychain has empty service entry
-              [weakKeychain.cachedKeychainData setObject:[@{} mutableCopy] forKey:service];
-              // Query the item
-              data = [weakKeychain dataForService:service account:account];
-              XCTAssertEqualObjects(data, tokenData);
-              // Cache should have the query item.
-              XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
-                                    tokenData);
-
-              // Clean up keychain at the end
-              [weakKeychain removeItemsMatchingService:@"*"
-                                               account:@"*"
-                                               handler:^(NSError *_Nonnull error) {
-                                                 XCTAssertNil(error);
-                                                 [addItemToKeychainExpectation fulfill];
-                                               }];
-            }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-}
-
-- (void)testCachedKeychainOverwrite {
-  XCTestExpectation *overwriteCachedKeychainExpectation =
-      [self expectationWithDescription:@"Test the cached keychain item is overwrite properly"];
-
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-
-  // Set the cache a different data under the same service but different account
-  NSData *data = [[NSData alloc] init];
-  NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-
-  [keychain.cachedKeychainData setObject:[@{kBundleID2 : data} mutableCopy] forKey:service];
-
-  // Create a keychain item
-  NSString *account = kBundleID1;
-  NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                    scope:kScope
-                                                    token:kToken1];
-  __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
-  [keychain setData:tokenData
-         forService:service
-            account:account
-            handler:^(NSError *error) {
-              XCTAssertNil(error);
-
-              // Query the item should fetch from keychain because no entry under the same
-              // service and account.
-              NSData *data = [weakKeychain dataForService:service account:account];
-              XCTAssertEqualObjects(data, tokenData);
-
-              // Cache should now have the query item
-              XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
-                                    tokenData);
-
-              // Clean up keychain at the end
-              [weakKeychain removeItemsMatchingService:@"*"
-                                               account:@"*"
-                                               handler:^(NSError *_Nonnull error) {
-                                                 XCTAssertNil(error);
-                                                 [overwriteCachedKeychainExpectation fulfill];
-                                               }];
-            }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-}
-
-- (void)testSetKeychainItemShouldDeleteOldEntry {
-  XCTestExpectation *overwriteCachedKeychainExpectation = [self
-      expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
-
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-
-  // Assume keychain had a old entry under the same service and account.
-  // Now if we set the cache a different data under the same service
-  NSData *oldData = [[NSData alloc] init];
-  NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-  NSString *account = kBundleID1;
-  [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
-  // add a new keychain item
-  NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
-                                                    scope:kScope
-                                                    token:kToken1];
-  __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
-  [keychain setData:tokenData
-         forService:service
-            account:account
-            handler:^(NSError *error) {
-              XCTAssertNil(error);
-
-              // Cache should now have the updated item
-              XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
-                                    tokenData);
-
-              // Clean up keychain at the end
-              [weakKeychain removeItemsMatchingService:@"*"
-                                               account:@"*"
-                                               handler:^(NSError *_Nonnull error) {
-                                                 XCTAssertNil(error);
-                                                 [overwriteCachedKeychainExpectation fulfill];
-                                               }];
-            }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-}
-
-- (void)testInvalidQuery {
-  XCTestExpectation *invalidKeychainQueryExpectation =
-      [self expectationWithDescription:@"Test invalid keychain query"];
-
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-
-  NSData *data = [[NSData alloc] init];
-  [keychain setData:data
-         forService:@"*"
-            account:@"*"
-            handler:^(NSError *error) {
-              XCTAssertNotNil(error);
-              [invalidKeychainQueryExpectation fulfill];
-            }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-}
-
-- (void)testQueryAndAddEntry {
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
-
-  // Set the cache a different data under the same service but different account
-  NSData *data = [[NSData alloc] init];
-  NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
-  NSString *account1 = kBundleID1;
-
-  [keychain.cachedKeychainData setObject:[@{account1 : data} mutableCopy] forKey:service];
-  // Now account2 doesn't exist in cache
-  NSString *account2 = kBundleID2;
-  XCTAssertNil(keychain.cachedKeychainData[service][account2]);
-  // Query account2
-  XCTAssertNil([keychain dataForService:service account:account2]);
-  // Service and account2 should exist in cache.
-  XCTAssertNotNil(keychain.cachedKeychainData[service][account2]);
-}
-
-#pragma mark - helper function
-- (NSData *)tokenDataWithAuthorizedEntity:(NSString *)authorizedEntity
-                                    scope:(NSString *)scope
-                                    token:(NSString *)token {
-  FIRInstanceIDTokenInfo *tokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
-                                                         scope:scope
-                                                         token:token
-                                                    appVersion:@"1.0"
-                                                 firebaseAppID:kFirebaseAppID];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  return [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
-#pragma clang diagnostic pop
-}
-@end
-
-#endif  // TARGET_OS_MACCATALYST

+ 0 - 400
Example/InstanceID/Tests/FIRInstanceIDAuthServiceTest.m

@@ -1,400 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-
-static NSString *const kDeviceAuthId = @"device-id";
-static NSString *const kSecretToken = @"secret-token";
-static NSString *const kVersionInfo = @"1.0";
-
-@interface FIRInstanceIDCheckinService ()
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinPreferences *checkinPreferences;
-@end
-
-@interface FIRInstanceIDAuthService ()
-@property(atomic, readwrite, assign) int64_t lastCheckinTimestampSeconds;
-@property(atomic, readwrite, assign) int64_t nextScheduledCheckinIntervalSeconds;
-@property(atomic, readwrite, assign) int checkinRetryCount;
-@property(nonatomic, readonly, strong)
-    NSMutableArray<FIRInstanceIDDeviceCheckinCompletion> *checkinHandlers;
-@end
-
-@interface FIRInstanceIDAuthServiceTest : XCTestCase
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDAuthService *authService;
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinService *checkinService;
-@property(nonatomic, readwrite, strong) id mockCheckinService;
-@property(nonatomic, readwrite, strong) id mockStore;
-@property(nonatomic, readwrite, copy) FIRInstanceIDDeviceCheckinCompletion checkinCompletion;
-
-@end
-
-@implementation FIRInstanceIDAuthServiceTest
-
-- (void)setUp {
-  [super setUp];
-
-  _mockStore = OCMClassMock([FIRInstanceIDStore class]);
-  _checkinService = [[FIRInstanceIDCheckinService alloc] init];
-  _mockCheckinService = OCMPartialMock(_checkinService);
-  _authService = [[FIRInstanceIDAuthService alloc] initWithCheckinService:_mockCheckinService
-                                                                    store:_mockStore];
-  // The tests here are to focus on checkin interval not locale change, so always set locale as
-  // non-changed.
-  [[NSUserDefaults standardUserDefaults] setObject:FIRInstanceIDCurrentLocale()
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-}
-
-- (void)tearDown {
-  _checkinCompletion = nil;
-  [super tearDown];
-}
-
-/**
- *  Test scheduling a checkin which completes successfully. Once the checkin is complete
- *  we should have the valid checkin preferences in memory.
- */
-- (void)testScheduleCheckin_initialSuccess {
-  XCTestExpectation *checkinExpectation =
-      [self expectationWithDescription:@"Did call checkin service"];
-
-  FIRInstanceIDCheckinPreferences *checkinPreferences = [self validCheckinPreferences];
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    self.checkinCompletion(checkinPreferences, nil);
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       [checkinExpectation fulfill];
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  [self.authService scheduleCheckin:YES];
-
-  XCTAssertTrue([self.authService hasValidCheckinInfo]);
-  XCTAssertEqual([self.authService checkinRetryCount], 1);
-  [self waitForExpectationsWithTimeout:2.0 handler:NULL];
-}
-
-/**
- *  Test scheduling a checkin which completes successfully, but fails to save, due to Keychain
- *  errors.
- */
-- (void)testScheduleCheckin_successButFailureInSaving {
-  XCTestExpectation *checkinFailureExpectation =
-      [self expectationWithDescription:@"Did receive error after checkin"];
-
-  FIRInstanceIDCheckinPreferences *checkinPreferences = [self validCheckinPreferences];
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    self.checkinCompletion(checkinPreferences, nil);
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return NO for whether we succeeded in persisting the checkin, to simulate Keychain error
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[OCMArg any], nil]];
-
-  [self.authService
-      fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *checkin, NSError *error) {
-        [checkinFailureExpectation fulfill];
-      }];
-
-  [self waitForExpectationsWithTimeout:2.0 handler:NULL];
-  XCTAssertFalse([self.authService hasValidCheckinInfo]);
-}
-
-/**
- *  Test scheduling multiple checkins to complete immediately. Each successive checkin should
- *  be triggered immediately.
- */
-- (void)testMultipleScheduleCheckin_immediately {
-  XCTestExpectation *checkinExpectation =
-      [self expectationWithDescription:@"Did call checkin service"];
-  __block int checkinHandlerInvocationCount = 0;
-
-  FIRInstanceIDCheckinPreferences *checkinPreferences = [self validCheckinPreferences];
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    checkinHandlerInvocationCount++;
-    // Mock successful Checkin after delay.
-    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
-                   dispatch_get_main_queue(), ^{
-                     [checkinExpectation fulfill];
-                     self.checkinCompletion(checkinPreferences, nil);
-                   });
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-  [self.authService scheduleCheckin:YES];
-
-  // Schedule an immediate checkin again.
-  // This should just return because the previous checkin isn't over yet.
-  [self.authService scheduleCheckin:YES];
-
-  [self waitForExpectationsWithTimeout:5.0 handler:NULL];
-  XCTAssertTrue([self.authService hasValidCheckinInfo]);
-  XCTAssertEqual([self.authService checkinRetryCount], 2);
-
-  // Checkin handler should only be invoked once since the second checkin request should
-  // return immediately.
-  XCTAssertEqual(checkinHandlerInvocationCount, 1);
-}
-
-/**
- *  Test multiple checkins scheduled. The second checkin should be scheduled after some
- *  delay before the first checkin has returned. Since the latter checkin is not immediate
- *  we should not run it since the first checkin is already scheduled to be executed later.
- */
-- (void)testMultipleScheduleCheckin_notImmediately {
-  XCTestExpectation *checkinExpectation =
-      [self expectationWithDescription:@"Did call checkin service"];
-
-  FIRInstanceIDCheckinPreferences *checkinPreferences = [self validCheckinPreferences];
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    // Mock successful Checkin after delay.
-    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
-                   dispatch_get_main_queue(), ^{
-                     [checkinExpectation fulfill];
-                     self.checkinCompletion(checkinPreferences, nil);
-                   });
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  [self.authService scheduleCheckin:YES];
-
-  // Schedule another checkin after some delay while the first checkin has not yet returned
-  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),
-                 dispatch_get_main_queue(), ^{
-                   [self.authService scheduleCheckin:NO];
-                 });
-
-  [self waitForExpectationsWithTimeout:5.0 handler:NULL];
-  XCTAssertTrue([self.authService hasValidCheckinInfo]);
-  XCTAssertEqual([self.authService checkinRetryCount], 1);
-}
-
-/**
- *  Test initial checkin failure which schedules another checkin which should succeed.
- */
-- (void)testInitialCheckinFailure_retrySuccess {
-  XCTestExpectation *checkinExpectation =
-      [self expectationWithDescription:@"Did call checkin service"];
-  __block int checkinHandlerInvocationCount = 0;
-
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    checkinHandlerInvocationCount++;
-
-    if (checkinHandlerInvocationCount == 1) {
-      // Mock failure on first try
-      NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
-      self.checkinCompletion(nil, error);
-    } else if (checkinHandlerInvocationCount == 2) {
-      // Mock success on second try
-      [checkinExpectation fulfill];
-      self.checkinCompletion([self validCheckinPreferences], nil);
-    } else {
-      // We should not retry for a third time again.
-      XCTFail(@"Invoking checkin handler invalid number of times.");
-    }
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  [self.authService scheduleCheckin:YES];
-  // Schedule another checkin after some delay while the first checkin has not yet returned
-  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
-                 dispatch_get_main_queue(), ^{
-                   [self.authService scheduleCheckin:YES];
-                   XCTAssertTrue([self.authService hasValidCheckinInfo]);
-                   XCTAssertEqual([self.authService checkinRetryCount], 2);
-                   XCTAssertEqual(checkinHandlerInvocationCount, 2);
-                 });
-
-  [self waitForExpectationsWithTimeout:5.0 handler:NULL];
-}
-
-/**
- *  Test initial checkin failure which schedules another checkin which should succeed. If
- *  a new checkin request comes after that we should not schedule a checkin as we have
- *  already have valid checkin credentials.
- */
-- (void)testInitialCheckinFailure_multipleRetrySuccess {
-  XCTestExpectation *checkinExpectation =
-      [self expectationWithDescription:@"Did call checkin service"];
-  __block int checkinHandlerInvocationCount = 0;
-
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    checkinHandlerInvocationCount++;
-
-    if (checkinHandlerInvocationCount <= 2) {
-      // Mock failure on first try
-      NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
-      self.checkinCompletion(nil, error);
-    } else if (checkinHandlerInvocationCount == 3) {
-      // Mock success on second try
-      [checkinExpectation fulfill];
-      self.checkinCompletion([self validCheckinPreferences], nil);
-    } else {
-      // We should not retry for a third time again.
-      XCTFail(@"Invoking checkin handler invalid number of times.");
-    }
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  [self.authService scheduleCheckin:YES];
-
-  [self waitForExpectationsWithTimeout:10.0 handler:NULL];
-  XCTAssertTrue([self.authService hasValidCheckinInfo]);
-  XCTAssertEqual([self.authService checkinRetryCount], 3);
-}
-
-/**
- * Performing multiple checkin requests should result in multiple handlers being
- * called back, but with only a single actual checkin fetch.
- */
-- (void)testMultipleCheckinHandlersWithSuccessfulCheckin {
-  XCTestExpectation *allHandlersCalledExpectation =
-      [self expectationWithDescription:@"All checkin handlers were called"];
-  __block NSInteger checkinHandlerCallbackCount = 0;
-  __block NSInteger checkinServiceInvocationCount = 0;
-
-  // Always return a successful checkin, and count the number of times CheckinService is called
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    checkinServiceInvocationCount++;
-    self.checkinCompletion([self validCheckinPreferences], nil);
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  NSInteger numHandlers = 10;
-  for (NSInteger i = 0; i < numHandlers; i++) {
-    [self.authService
-        fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *checkin, NSError *error) {
-          checkinHandlerCallbackCount++;
-          if (checkinHandlerCallbackCount == numHandlers) {
-            [allHandlersCalledExpectation fulfill];
-          }
-        }];
-  }
-
-  [self waitForExpectationsWithTimeout:1.0 handler:nil];
-  XCTAssertEqual(checkinServiceInvocationCount, 1);
-  XCTAssertEqual(checkinHandlerCallbackCount, numHandlers);
-}
-
-/**
- * Performing a scheduled checkin *and* simultaneous checkin request should result in
- * the number of pending checkin handlers to be 2 (one for the scheduled checkin, one for
- * the direct fetch).
- */
-- (void)testScheduledAndImmediateCheckinsWithMultipleHandler {
-  XCTestExpectation *fetchHandlerCalledExpectation =
-      [self expectationWithDescription:@"Direct checkin handler was called"];
-  __block NSInteger checkinServiceInvocationCount = 0;
-
-  // Always return a successful checkin, and count the number of times CheckinService is called
-  [[[self.mockCheckinService stub] andDo:^(NSInvocation *invocation) {
-    checkinServiceInvocationCount++;
-    // Give the checkin service some time to complete the request
-    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)),
-                   dispatch_get_main_queue(), ^{
-                     self.checkinCompletion([self validCheckinPreferences], nil);
-                   });
-  }] checkinWithExistingCheckin:[OCMArg any]
-                     completion:[OCMArg checkWithBlock:^BOOL(id obj) {
-                       self.checkinCompletion = obj;
-                       return obj != nil;
-                     }]];
-
-  // Always return YES for whether we succeeded in persisting the checkin
-  [[self.mockStore stub] saveCheckinPreferences:[OCMArg any]
-                                        handler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-
-  // Start a scheduled (though immediate) checkin
-  [self.authService scheduleCheckin:YES];
-
-  // Request a direct checkin fetch
-  [self.authService
-      fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *checkin, NSError *error) {
-        [fetchHandlerCalledExpectation fulfill];
-      }];
-  // At this point we should have checkinHandlers, one for scheduled, one for the direct fetch
-  XCTAssertEqual(self.authService.checkinHandlers.count, 2);
-
-  [self waitForExpectationsWithTimeout:0.5 handler:nil];
-  // Make sure only one checkin fetch was performed
-  XCTAssertEqual(checkinServiceInvocationCount, 1);
-}
-
-#pragma mark - Helper Methods
-
-- (FIRInstanceIDCheckinPreferences *)validCheckinPreferences {
-  NSDictionary *gservicesData = @{
-    kFIRInstanceIDVersionInfoStringKey : kVersionInfo,
-    kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
-  };
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  [checkinPreferences updateWithCheckinPlistContents:gservicesData];
-  return checkinPreferences;
-}
-
-@end

+ 0 - 109
Example/InstanceID/Tests/FIRInstanceIDBackupExcludedPlistTest.m

@@ -1,109 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-
-static NSString *const kSubDirectoryName = @"FirebaseInstanceIDBackupPlistTest";
-static NSString *const kTestPlistFileName = @"com.google.test.IIDBackupExcludedPlist";
-
-@interface FIRInstanceIDBackupExcludedPlist ()
-- (BOOL)moveToApplicationSupportSubDirectory:(NSString *)subDirectoryName;
-@end
-
-@interface FIRInstanceIDBackupExcludedPlistTest : XCTestCase
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDBackupExcludedPlist *plist;
-
-@end
-
-@implementation FIRInstanceIDBackupExcludedPlistTest
-
-- (void)setUp {
-  [super setUp];
-  [FIRInstanceIDStore createSubDirectory:kSubDirectoryName];
-  self.plist = [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:kTestPlistFileName
-                                                             subDirectory:kSubDirectoryName];
-}
-
-- (void)tearDown {
-  [self.plist deleteFile:nil];
-  [FIRInstanceIDStore removeSubDirectory:kSubDirectoryName error:nil];
-  [super tearDown];
-}
-
-- (void)testWriteToPlistInDocumentsFolder {
-  XCTAssertNil([self.plist contentAsDictionary]);
-  NSDictionary *plistContents = @{@"hello" : @"world", @"id" : @123};
-  [self.plist writeDictionary:plistContents error:nil];
-  XCTAssertEqualObjects(plistContents, [self.plist contentAsDictionary]);
-}
-
-- (void)testDeleteFileInDocumentsFolder {
-  NSDictionary *plistContents = @{@"hello" : @"world", @"id" : @123};
-  [self.plist writeDictionary:plistContents error:nil];
-  XCTAssertEqualObjects(plistContents, [self.plist contentAsDictionary]);
-
-  // Delete file
-  XCTAssertTrue([self.plist doesFileExist]);
-  XCTAssertTrue([self.plist deleteFile:nil]);
-  XCTAssertFalse([self.plist doesFileExist]);
-}
-
-- (void)testWriteToPlistInApplicationSupportFolder {
-  XCTAssertNil([self.plist contentAsDictionary]);
-
-  NSDictionary *plistContents = @{@"hello" : @"world", @"id" : @123};
-  [self.plist writeDictionary:plistContents error:nil];
-
-  XCTAssertTrue([self.plist doesFileExist]);
-  XCTAssertEqualObjects(plistContents, [self.plist contentAsDictionary]);
-
-  XCTAssertTrue([self doesPlistFileExist]);
-}
-
-#pragma mark - Private Helpers
-
-- (BOOL)doesPlistFileExist {
-#if TARGET_OS_TV
-  NSArray *directoryPaths =
-      NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
-#else
-  NSArray *directoryPaths =
-      NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
-#endif
-  NSString *dirPath = directoryPaths.lastObject;
-  NSArray *components =
-      @[ dirPath, kSubDirectoryName, [NSString stringWithFormat:@"%@.plist", kTestPlistFileName] ];
-  NSString *plistPath = [NSString pathWithComponents:components];
-  return [[NSFileManager defaultManager] fileExistsAtPath:plistPath];
-}
-
-- (BOOL)isPlistInDocumentsDirectory {
-  NSArray *directoryPaths =
-      NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
-  NSString *documentsSupportDirPath = directoryPaths.lastObject;
-  NSArray *components =
-      @[ documentsSupportDirPath, [NSString stringWithFormat:@"%@.plist", kTestPlistFileName] ];
-  NSString *plistPath = [NSString pathWithComponents:components];
-  return [[NSFileManager defaultManager] fileExistsAtPath:plistPath];
-}
-
-@end

+ 0 - 88
Example/InstanceID/Tests/FIRInstanceIDCheckinPreferencesTest.m

@@ -1,88 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-
-static NSString *const kDeviceAuthId = @"1234";
-static NSString *const kSecretToken = @"567890";
-
-@interface FIRInstanceIDCheckinPreferencesTest : XCTestCase
-
-@end
-
-@implementation FIRInstanceIDCheckinPreferencesTest
-
-- (void)setUp {
-  [super setUp];
-}
-
-- (void)tearDown {
-  [super tearDown];
-}
-
-- (void)testInvalidCheckinInfo {
-  FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:@"" secretToken:@""];
-  XCTAssertFalse([preferences hasValidCheckinInfo]);
-}
-
-- (void)testCheckinPreferencesReset {
-  FIRInstanceIDCheckinPreferences *checkin =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  [checkin reset];
-  XCTAssertNil(checkin.deviceID);
-  XCTAssertNil(checkin.secretToken);
-  XCTAssertFalse([checkin hasValidCheckinInfo]);
-}
-
-- (void)testInvalidCheckinInfoDueToLocaleChanged {
-  // Set to a different locale than the current locale.
-  [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hant"
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  FIRInstanceIDCheckinPreferences *checkin =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  XCTAssertFalse([checkin hasValidCheckinInfo],
-                 @"Should consider checkin info invalid as locale has changed.");
-  // set back the original locale
-  [[NSUserDefaults standardUserDefaults] setObject:FIRInstanceIDCurrentLocale()
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-}
-
-- (void)testCheckinPreferenceRefreshTokenWeekly {
-  FIRInstanceIDCheckinPreferences *checkin =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  int64_t now = FIRInstanceIDCurrentTimestampInMilliseconds();
-  [checkin updateWithCheckinPlistContents:@{kFIRInstanceIDLastCheckinTimeKey : @(now)}];
-
-  XCTAssertTrue([checkin hasValidCheckinInfo]);
-
-  // Set last checkin time long time ago.
-  now = FIRInstanceIDCurrentTimestampInMilliseconds();
-  [checkin updateWithCheckinPlistContents:@{
-    kFIRInstanceIDLastCheckinTimeKey : @(now - kFIRInstanceIDDefaultCheckinInterval * 1000 - 1)
-  }];
-
-  XCTAssertFalse([checkin hasValidCheckinInfo]);
-}
-
-@end

+ 0 - 178
Example/InstanceID/Tests/FIRInstanceIDCheckinServiceTest.m

@@ -1,178 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-static NSString *const kDeviceAuthId = @"1234";
-static NSString *const kSecretToken = @"567890";
-static NSString *const kDigest = @"com.google.digest";
-static NSString *const kVersionInfo = @"1.0";
-
-@interface FIRInstanceIDCheckinServiceTest : XCTestCase
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinService *checkinService;
-
-@end
-
-@implementation FIRInstanceIDCheckinServiceTest
-
-- (void)setUp {
-  [super setUp];
-  self.checkinService = [[FIRInstanceIDCheckinService alloc] init];
-}
-
-- (void)tearDown {
-  self.checkinService = nil;
-  [super tearDown];
-}
-
-- (void)testCheckinWithSuccessfulCompletion {
-  FIRInstanceIDCheckinPreferences *existingCheckin = [self stubCheckinCacheWithValidData];
-
-  [FIRInstanceIDCheckinService setCheckinTestBlock:[self successfulCheckinCompletionHandler]];
-
-  XCTestExpectation *checkinCompletionExpectation =
-      [self expectationWithDescription:@"Checkin Completion"];
-
-  [self.checkinService
-      checkinWithExistingCheckin:existingCheckin
-                      completion:^(FIRInstanceIDCheckinPreferences *checkinPreferences,
-                                   NSError *error) {
-                        XCTAssertNil(error);
-                        XCTAssertEqualObjects(checkinPreferences.deviceID, kDeviceAuthId);
-                        XCTAssertEqualObjects(checkinPreferences.versionInfo, kVersionInfo);
-                        // For accuracy purposes it's better to compare seconds since the test
-                        // should never run for more than 1 second.
-                        NSInteger expectedTimestampInSeconds =
-                            (NSInteger)FIRInstanceIDCurrentTimestampInSeconds();
-                        NSInteger actualTimestampInSeconds =
-                            checkinPreferences.lastCheckinTimestampMillis / 1000.0;
-                        XCTAssertEqual(expectedTimestampInSeconds, actualTimestampInSeconds);
-                        XCTAssertTrue([checkinPreferences hasValidCheckinInfo]);
-                        [checkinCompletionExpectation fulfill];
-                      }];
-
-  [self waitForExpectationsWithTimeout:5
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-- (void)testFailedCheckinService {
-  [FIRInstanceIDCheckinService setCheckinTestBlock:[self failCheckinCompletionHandler]];
-
-  XCTestExpectation *checkinCompletionExpectation =
-      [self expectationWithDescription:@"Checkin Completion"];
-
-  [self.checkinService
-      checkinWithExistingCheckin:nil
-                      completion:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
-                        XCTAssertNotNil(error);
-                        XCTAssertNil(preferences.deviceID);
-                        XCTAssertNil(preferences.secretToken);
-                        XCTAssertFalse([preferences hasValidCheckinInfo]);
-                        [checkinCompletionExpectation fulfill];
-                      }];
-
-  [self waitForExpectationsWithTimeout:5
-                               handler:^(NSError *error) {
-                                 if (error) {
-                                   XCTFail(@"Checkin Timeout Error: %@", error);
-                                 }
-                               }];
-}
-
-- (void)testCheckinServiceFailsWithErrorAfterStopFetching {
-  [self.checkinService stopFetching];
-
-  XCTestExpectation *checkinCompletionExpectation =
-      [self expectationWithDescription:@"Checkin Completion"];
-
-  [self.checkinService
-      checkinWithExistingCheckin:nil
-                      completion:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
-                        [checkinCompletionExpectation fulfill];
-                        XCTAssertNil(preferences);
-                        XCTAssertNotNil(error);
-                        XCTAssertEqual(error.code, kFIRInstanceIDErrorCodeRegistrarFailedToCheckIn);
-                      }];
-
-  [self waitForExpectationsWithTimeout:5
-                               handler:^(NSError *error) {
-                                 if (error) {
-                                   XCTFail(@"Checkin Timeout Error: %@", error);
-                                 }
-                               }];
-}
-
-#pragma mark - Stub
-
-- (FIRInstanceIDCheckinPreferences *)stubCheckinCacheWithValidData {
-  NSDictionary *gservicesData = @{
-    @"FIRInstanceIDVersionInfo" : kVersionInfo,
-    @"FIRInstanceIDLastCheckinTimestampKey" : @(FIRInstanceIDCurrentTimestampInMilliseconds())
-  };
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  [checkinPreferences updateWithCheckinPlistContents:gservicesData];
-  return checkinPreferences;
-}
-
-#pragma mark - Swizzle
-
-- (FIRInstanceIDURLRequestTestBlock)successfulCheckinCompletionHandler {
-  return ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock testResponse) {
-    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                              statusCode:200
-                                                             HTTPVersion:@"HTTP/1.1"
-                                                            headerFields:nil];
-
-    NSMutableDictionary *dataResponse = [NSMutableDictionary dictionary];
-    dataResponse[@"android_id"] = @([kDeviceAuthId longLongValue]);
-    dataResponse[@"security_token"] = @([kSecretToken longLongValue]);
-    dataResponse[@"time_msec"] = @(FIRInstanceIDCurrentTimestampInMilliseconds());
-    dataResponse[@"version_info"] = kVersionInfo;
-    dataResponse[@"digest"] = kDigest;
-    NSData *data = [NSJSONSerialization dataWithJSONObject:dataResponse
-                                                   options:NSJSONWritingPrettyPrinted
-                                                     error:nil];
-    testResponse(data, response, nil);
-  };
-}
-
-- (FIRInstanceIDURLRequestTestBlock)failCheckinCompletionHandler {
-  return ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock testResponse) {
-    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                              statusCode:200
-                                                             HTTPVersion:@"HTTP/1.1"
-                                                            headerFields:nil];
-
-    NSError *error =
-        [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidRequest];
-
-    testResponse(nil, response, error);
-  };
-}
-
-@end

+ 0 - 225
Example/InstanceID/Tests/FIRInstanceIDCheckinStoreTest.m

@@ -1,225 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-
-#import "Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h"
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-static const NSTimeInterval kExpectationTimeout = 12;
-
-@interface FIRInstanceIDCheckinStore ()
-- (NSString *)bundleIdentifierForKeychainAccount;
-@end
-
-// Testing constants
-static NSString *const kFakeCheckinPlistName = @"com.google.test.IIDStoreTestCheckin";
-static NSString *const kSubDirectoryName = @"FirebaseInstanceIDCheckinTest";
-
-static NSString *const kAuthID = @"test-auth-id";
-static NSString *const kDigest = @"test-digest";
-static NSString *const kSecret = @"test-secret";
-static NSString *const kFakeErrorDomain = @"fakeDomain";
-static const NSUInteger kFakeErrorCode = -1;
-
-static int64_t const kLastCheckinTimestamp = 123456;
-
-@interface FIRInstanceIDCheckinStoreTest : XCTestCase
-
-@end
-
-@implementation FIRInstanceIDCheckinStoreTest
-
-- (void)setUp {
-  [super setUp];
-  [FIRInstanceIDStore createSubDirectory:kSubDirectoryName];
-}
-
-- (void)tearDown {
-  NSString *path = [self pathForCheckinPlist];
-  if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
-    NSError *error;
-    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
-  }
-  [FIRInstanceIDStore removeSubDirectory:kSubDirectoryName error:nil];
-  [super tearDown];
-}
-
-/**
- *  Keychain read failure should lead to checkin preferences with invalid credentials.
- */
-- (void)testInvalidCheckinPreferencesOnKeychainFail {
-  XCTestExpectation *checkinInvalidExpectation = [self
-      expectationWithDescription:@"Checkin preference should be invalid after keychain failure"];
-  FIRInstanceIDBackupExcludedPlist *checkinPlist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:kFakeCheckinPlistName
-                                                    subDirectory:kSubDirectoryName];
-
-  FIRInstanceIDFakeKeychain *fakeKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-
-  FIRInstanceIDCheckinStore *checkinStore =
-      [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:checkinPlist keychain:fakeKeychain];
-  __block FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:[[self class] newCheckinPlistPreferences]];
-  [checkinStore saveCheckinPreferences:preferences
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                                 fakeKeychain.cannotReadFromKeychain = YES;
-                                 preferences = [checkinStore cachedCheckinPreferences];
-
-                                 XCTAssertNil(preferences.deviceID);
-                                 XCTAssertNil(preferences.secretToken);
-                                 XCTAssertFalse([preferences hasValidCheckinInfo]);
-
-                                 [checkinInvalidExpectation fulfill];
-                               }];
-  [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
-}
-
-/**
- *  CheckinStore should not be able to save the checkin preferences if the write to the
- *  Keychain fails.
- */
-- (void)testCheckinSaveFailsOnKeychainWriteFailure {
-  XCTestExpectation *checkinSaveFailsExpectation =
-      [self expectationWithDescription:@"Checkin save should fail after keychain write failure"];
-  FIRInstanceIDBackupExcludedPlist *checkinPlist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:kFakeCheckinPlistName
-                                                    subDirectory:kSubDirectoryName];
-  FIRInstanceIDFakeKeychain *fakeKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-  fakeKeychain.cannotWriteToKeychain = YES;
-
-  FIRInstanceIDCheckinStore *checkinStore =
-      [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:checkinPlist keychain:fakeKeychain];
-
-  __block FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:[[self class] newCheckinPlistPreferences]];
-  [checkinStore saveCheckinPreferences:preferences
-                               handler:^(NSError *error) {
-                                 XCTAssertNotNil(error);
-
-                                 preferences = [checkinStore cachedCheckinPreferences];
-                                 XCTAssertNil(preferences.deviceID);
-                                 XCTAssertNil(preferences.secretToken);
-                                 XCTAssertFalse([preferences hasValidCheckinInfo]);
-                                 [checkinSaveFailsExpectation fulfill];
-                               }];
-  [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
-}
-
-- (void)testCheckinSaveFailsOnPlistWriteFailure {
-  XCTestExpectation *checkinSaveFailsExpectation =
-      [self expectationWithDescription:@"Checkin save should fail after plist write failure"];
-  FIRInstanceIDBackupExcludedPlist *checkinPlist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:kFakeCheckinPlistName
-                                                    subDirectory:kSubDirectoryName];
-  id plistMock = OCMPartialMock(checkinPlist);
-  NSError *error = [NSError errorWithDomain:kFakeErrorDomain code:kFakeErrorCode userInfo:nil];
-  OCMStub([plistMock writeDictionary:[OCMArg any] error:[OCMArg setTo:error]]).andReturn(NO);
-
-  FIRInstanceIDFakeKeychain *fakeKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-
-  FIRInstanceIDCheckinStore *checkinStore =
-      [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:plistMock keychain:fakeKeychain];
-
-  __block FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:[[self class] newCheckinPlistPreferences]];
-  [checkinStore saveCheckinPreferences:preferences
-                               handler:^(NSError *error) {
-                                 XCTAssertNotNil(error);
-                                 XCTAssertEqual(error.code, kFakeErrorCode);
-
-                                 preferences = [checkinStore cachedCheckinPreferences];
-                                 XCTAssertNil(preferences.deviceID);
-                                 XCTAssertNil(preferences.secretToken);
-                                 XCTAssertFalse([preferences hasValidCheckinInfo]);
-                                 [checkinSaveFailsExpectation fulfill];
-                               }];
-  [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
-}
-
-- (void)testCheckinSaveSuccess {
-  XCTestExpectation *checkinSaveSuccessExpectation =
-      [self expectationWithDescription:@"Checkin save should succeed"];
-  FIRInstanceIDBackupExcludedPlist *checkinPlist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:kFakeCheckinPlistName
-                                                    subDirectory:kSubDirectoryName];
-  id plistMock = OCMPartialMock(checkinPlist);
-
-  FIRInstanceIDFakeKeychain *fakeKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-  FIRInstanceIDCheckinStore *checkinStore =
-      [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:plistMock keychain:fakeKeychain];
-
-  __block FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:[[self class] newCheckinPlistPreferences]];
-  [checkinStore saveCheckinPreferences:preferences
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-
-                                 preferences = [checkinStore cachedCheckinPreferences];
-                                 XCTAssertEqualObjects(preferences.deviceID, kAuthID);
-                                 XCTAssertEqualObjects(preferences.secretToken, kSecret);
-                                 [checkinSaveSuccessExpectation fulfill];
-                               }];
-  [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
-}
-
-#pragma mark - Private Helpers
-
-- (BOOL)savePreferencesToPlist:(NSDictionary *)preferences {
-  NSString *path = [self pathForCheckinPlist];
-  return [preferences writeToFile:path atomically:YES];
-}
-
-- (NSString *)pathForCheckinPlist {
-  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
-  NSString *plistNameWithExtension = [NSString stringWithFormat:@"%@.plist", kFakeCheckinPlistName];
-  return [paths[0] stringByAppendingPathComponent:plistNameWithExtension];
-}
-
-+ (NSDictionary *)checkinPreferences {
-  return @{
-    kFIRInstanceIDDeviceAuthIdKey : kAuthID,
-    kFIRInstanceIDSecretTokenKey : kSecret,
-    kFIRInstanceIDDigestStringKey : kDigest,
-    kFIRInstanceIDGServicesDictionaryKey : @{},
-    kFIRInstanceIDLastCheckinTimeKey : @(kLastCheckinTimestamp),
-  };
-}
-
-+ (NSDictionary *)newCheckinPlistPreferences {
-  NSMutableDictionary *oldPreferences = [[self checkinPreferences] mutableCopy];
-  [oldPreferences removeObjectForKey:kFIRInstanceIDDeviceAuthIdKey];
-  [oldPreferences removeObjectForKey:kFIRInstanceIDSecretTokenKey];
-  oldPreferences[kFIRInstanceIDLastCheckinTimeKey] =
-      @(FIRInstanceIDCurrentTimestampInMilliseconds() - 1000);
-  return [oldPreferences copy];
-}
-
-@end

+ 0 - 28
Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h

@@ -1,28 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-
-@interface FIRInstanceIDFakeKeychain : FIRInstanceIDAuthKeychain
-
-// Flags to simulate problems when reading from or writing to Keychain.
-// By default you can always read/write to the Keychain.
-@property(nonatomic, readwrite, assign) BOOL cannotReadFromKeychain;
-@property(nonatomic, readwrite, assign) BOOL cannotWriteToKeychain;
-
-@end

+ 0 - 111
Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.m

@@ -1,111 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h"
-
-static NSString *const kFakeKeychainErrorDomain = @"com.google.iid";
-
-@interface FIRInstanceIDFakeKeychain ()
-
-@property(nonatomic, readwrite, strong) NSMutableDictionary *data;
-
-@end
-
-@implementation FIRInstanceIDFakeKeychain
-
-- (instancetype)init {
-  self = [super init];
-  if (self) {
-    _data = [NSMutableDictionary dictionary];
-  }
-  return self;
-}
-
-- (NSArray<NSData *> *)itemsMatchingService:(NSString *)service account:(NSString *)account {
-  if (self.cannotReadFromKeychain) {
-    return @[];
-  }
-  NSMutableArray<NSData *> *results = [NSMutableArray array];
-  BOOL accountIsWildcard = [account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier];
-  BOOL serviceIsWildcard = [service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier];
-  for (NSString *accountKey in [self.data allKeys]) {
-    if (!accountIsWildcard && ![accountKey isEqualToString:account]) {
-      continue;
-    }
-    NSDictionary *services = self.data[accountKey];
-    for (NSString *serviceKey in [services allKeys]) {
-      if (!serviceIsWildcard && ![serviceKey isEqualToString:service]) {
-        continue;
-      }
-      NSData *item = self.data[accountKey][serviceKey];
-      [results addObject:item];
-    }
-  }
-  return results;
-}
-
-- (NSData *)dataForService:(NSString *)service account:(NSString *)account {
-  if (self.cannotReadFromKeychain) {
-    return nil;
-  }
-  return self.data[account][service];
-}
-
-- (void)removeItemsMatchingService:(NSString *)service
-                           account:(NSString *)account
-                           handler:(void (^)(NSError *error))handler {
-  if (self.cannotWriteToKeychain) {
-    if (handler) {
-      handler([NSError errorWithDomain:kFakeKeychainErrorDomain code:1001 userInfo:nil]);
-    }
-    return;
-  }
-  if ([account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-    // Remove all account keys.
-    [self.data removeAllObjects];
-  } else {
-    if ([service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-      // Remove all service keys for this account key.
-      [self.data[account] removeAllObjects];
-    } else {
-      [self.data[account] removeObjectForKey:service];
-    }
-  }
-  if (handler) {
-    handler(nil);
-  }
-}
-
-- (void)setData:(NSData *)data
-     forService:(NSString *)service
-        account:(NSString *)account
-        handler:(void (^)(NSError *error))handler {
-  if (self.cannotWriteToKeychain) {
-    if (handler) {
-      handler([NSError errorWithDomain:kFakeKeychainErrorDomain code:1001 userInfo:nil]);
-    }
-    return;
-  }
-  if (!self.data[account]) {
-    self.data[account] = [NSMutableDictionary dictionary];
-  }
-  self.data[account][service] = data;
-  if (handler) {
-    handler(nil);
-  }
-}
-
-@end

+ 0 - 144
Example/InstanceID/Tests/FIRInstanceIDResultTest.m

@@ -1,144 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/Public/FIRInstanceID.h"
-
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-
-static NSString *const kFakeIID = @"fE1e1PZJFSQ";
-static NSString *const kFakeToken =
-    @"fE1e1PZJFSQ:APA91bFAOjp1ahBWn9rTlbjArwBEm_"
-    @"yUTTzK6dhIvLqzqqCSabaa4TQVM0pGTmF6r7tmMHPe6VYiGMHuCwJFgj5v97xl78sUNMLwuPPhoci8z_"
-    @"QGlCrTbxCFGzEUfvA3fGpGgIVQU2W6";
-
-@interface FIRInstanceID (ExposedForTest)
-- (NSString *)cachedTokenIfAvailable;
-- (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
-- (instancetype)initPrivately;
-- (void)start;
-@end
-
-@interface FIRInstanceIDResultTest : XCTestCase {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  FIRInstanceID *_instanceID;
-#pragma clang diagnostic pop
-
-  id _mockInstanceID;
-}
-
-@end
-
-@implementation FIRInstanceIDResultTest
-
-- (void)setUp {
-  [super setUp];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  _mockInstanceID = OCMClassMock([FIRInstanceID class]);
-#pragma clang diagnostic pop
-}
-
-- (void)tearDown {
-  [_mockInstanceID stopMocking];
-  _mockInstanceID = nil;
-  [super tearDown];
-}
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-- (void)testResultWithFailedIID {
-  // mocking getting iid failed with error.
-  OCMStub([_mockInstanceID
-      getIDWithHandler:([OCMArg invokeBlockWithArgs:[NSNull null],
-                                                    [NSError errorWithFIRInstanceIDErrorCode:100],
-                                                    nil])]);
-
-  [_instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        XCTAssertNil(result);
-        XCTAssertNotNil(error);
-        XCTAssertEqual(error.code, 100);
-      }];
-}
-
-- (void)testResultWithCacheToken {
-  // mocking getting iid succeed and a cache token exists.
-  OCMStub([_mockInstanceID
-      getIDWithHandler:([OCMArg invokeBlockWithArgs:kFakeIID, [NSNull null], nil])]);
-  OCMStub([_mockInstanceID cachedTokenIfAvailable]).andReturn(kFakeToken);
-  [_instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        XCTAssertNotNil(result);
-        XCTAssertNil(error);
-        XCTAssertEqualObjects(result.instanceID, kFakeIID);
-        XCTAssertEqualObjects(result.token, kFakeToken);
-      }];
-}
-
-- (void)testResultWithNewToken {
-  // mocking getting iid succeed and a new token is generated.
-  OCMStub([_mockInstanceID
-      getIDWithHandler:([OCMArg invokeBlockWithArgs:kFakeIID, [NSNull null], nil])]);
-  OCMStub([_mockInstanceID cachedTokenIfAvailable]).andReturn(nil);
-  OCMStub([_mockInstanceID
-      defaultTokenWithHandler:([OCMArg invokeBlockWithArgs:kFakeToken, [NSNull null], nil])]);
-  [_instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        XCTAssertNotNil(result);
-        XCTAssertNil(error);
-        XCTAssertEqualObjects(result.instanceID, kFakeIID);
-        XCTAssertEqualObjects(result.token, kFakeToken);
-      }];
-}
-
-- (void)testResultWithFailedFetchingToken {
-  // mock getting iid succeed and token fails
-  OCMStub([_mockInstanceID
-      getIDWithHandler:([OCMArg invokeBlockWithArgs:kFakeIID, [NSNull null], nil])]);
-  OCMStub([_mockInstanceID cachedTokenIfAvailable]).andReturn(nil);
-  OCMStub([_mockInstanceID
-      defaultTokenWithHandler:([OCMArg
-                                  invokeBlockWithArgs:[NSNull null],
-                                                      [NSError errorWithFIRInstanceIDErrorCode:200],
-                                                      nil])]);
-
-  [_instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        XCTAssertNil(result);
-        XCTAssertNotNil(error);
-        XCTAssertEqual(error.code, 200);
-      }];
-}
-
-- (void)testResultCanBeCoplied {
-  // mocking getting iid succeed and a cache token exists.
-  OCMStub([_mockInstanceID
-      getIDWithHandler:([OCMArg invokeBlockWithArgs:kFakeIID, [NSNull null], nil])]);
-  OCMStub([_mockInstanceID cachedTokenIfAvailable]).andReturn(kFakeToken);
-  [_instanceID
-      instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        FIRInstanceIDResult *resultCopy = [result copy];
-        XCTAssertEqualObjects(resultCopy.instanceID, kFakeIID);
-        XCTAssertEqualObjects(resultCopy.token, kFakeToken);
-      }];
-}
-#pragma clang diagnostic pop
-
-@end

+ 0 - 242
Example/InstanceID/Tests/FIRInstanceIDStoreTest.m

@@ -1,242 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h"
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-static NSString *const kSubDirectoryName = @"FirebaseInstanceIDStoreTest";
-
-static NSString *const kAuthorizedEntity = @"test-audience";
-static NSString *const kScope = @"test-scope";
-static NSString *const kToken = @"test-token";
-static NSString *const kAuthID = @"test-auth-id";
-static NSString *const kSecret = @"test-secret";
-
-@interface FIRInstanceIDStore ()
-
-- (NSString *)tokenWithKey:(NSString *)key;
-- (void)cacheToken:(NSString *)token withKey:(NSString *)key;
-
-// APNS
-+ (NSString *)legacyAPNSTokenCacheKeyForServerType:(BOOL)isSandbox;
-+ (NSData *)dataWithHexString:(NSString *)hex;
-
-- (void)resetCredentialsIfNeeded;
-- (BOOL)hasSavedLibraryVersion;
-- (BOOL)hasCheckinPlist;
-
-@end
-
-@interface FIRInstanceIDStoreTest : XCTestCase
-
-@property(strong, nonatomic) FIRInstanceIDStore *instanceIDStore;
-@property(strong, nonatomic) FIRInstanceIDBackupExcludedPlist *checkinPlist;
-@property(strong, nonatomic) FIRInstanceIDCheckinStore *checkinStore;
-@property(strong, nonatomic) FIRInstanceIDTokenStore *tokenStore;
-@property(strong, nonatomic) id mockCheckinStore;
-@property(strong, nonatomic) id mockTokenStore;
-@property(strong, nonatomic) id mockInstanceIDStore;
-
-@end
-
-@implementation FIRInstanceIDStoreTest
-
-- (void)setUp {
-  [super setUp];
-  [FIRInstanceIDStore createSubDirectory:kSubDirectoryName];
-
-  NSString *checkinPlistName = @"com.google.test.IIDStoreTestCheckin";
-  self.checkinPlist = [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:checkinPlistName
-                                                                    subDirectory:kSubDirectoryName];
-
-  // checkin store
-  FIRInstanceIDFakeKeychain *fakeKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-  _checkinStore = [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:self.checkinPlist
-                                                                 keychain:fakeKeychain];
-  _mockCheckinStore = OCMPartialMock(_checkinStore);
-  // token store
-  FIRInstanceIDFakeKeychain *fakeTokenKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-  _tokenStore = [[FIRInstanceIDTokenStore alloc] initWithKeychain:fakeTokenKeychain];
-  _mockTokenStore = OCMPartialMock(_tokenStore);
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wnonnull"
-  _instanceIDStore = [[FIRInstanceIDStore alloc] initWithCheckinStore:_mockCheckinStore
-                                                           tokenStore:_mockTokenStore
-                                                             delegate:nil];
-#pragma clang diagnostic pop
-  _mockInstanceIDStore = OCMPartialMock(_instanceIDStore);
-}
-
-- (void)tearDown {
-  [self.instanceIDStore removeAllCachedTokensWithHandler:nil];
-  [self.instanceIDStore removeCheckinPreferencesWithHandler:nil];
-  [FIRInstanceIDStore removeSubDirectory:kSubDirectoryName error:nil];
-  [_mockCheckinStore stopMocking];
-  [_mockTokenStore stopMocking];
-  [_mockInstanceIDStore stopMocking];
-  [super tearDown];
-}
-
-/**
- *  Tests that an InstanceID token can be stored in the FIRInstanceIDStore for
- *  an authorizedEntity and scope.
- */
-- (void)testSaveToken {
-  XCTestExpectation *tokenExpectation = [self expectationWithDescription:@"token is saved"];
-  FIRInstanceIDTokenInfo *tokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken
-                                                    appVersion:@"1.0"
-                                                 firebaseAppID:@"firebaseAppID"];
-  [self.instanceIDStore saveTokenInfo:tokenInfo
-                              handler:^(NSError *error) {
-                                XCTAssertNil(error);
-                                FIRInstanceIDTokenInfo *retrievedTokenInfo = [self.instanceIDStore
-                                    tokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                                            scope:kScope];
-                                XCTAssertEqualObjects(retrievedTokenInfo.token, kToken);
-                                [tokenExpectation fulfill];
-                              }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-}
-
-/**
- *  Tests that a token can be removed from from FIRInstanceIDStore's cache when specifying
- *  its authorizedEntity and scope.
- */
-- (void)testRemoveCachedToken {
-  XCTestExpectation *tokenExpectation = [self expectationWithDescription:@"token is removed"];
-  FIRInstanceIDTokenInfo *tokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken
-                                                    appVersion:@"1.0"
-                                                 firebaseAppID:@"firebaseAppID"];
-  [self.instanceIDStore
-      saveTokenInfo:tokenInfo
-            handler:^(NSError *error) {
-              XCTAssertNotNil([self.instanceIDStore tokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                                                            scope:kScope]);
-
-              [self.instanceIDStore removeCachedTokenWithAuthorizedEntity:kAuthorizedEntity
-                                                                    scope:kScope];
-              XCTAssertNil([self.instanceIDStore tokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                                                         scope:kScope]);
-              [tokenExpectation fulfill];
-            }];
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-}
-
-/**
- *  Tests that a checkin authentication ID can be stored in the FIRInstanceIDStore.
- */
-- (void)testSaveCheckinAuthID {
-  XCTestExpectation *checkinExpectation = [self expectationWithDescription:@"checkin is saved"];
-  NSDictionary *plistContent = @{
-    kFIRInstanceIDDigestStringKey : @"digest-xyz",
-    kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
-  };
-  FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:plistContent];
-  [self.instanceIDStore
-      saveCheckinPreferences:preferences
-                     handler:^(NSError *_Nonnull error) {
-                       XCTAssertNil(error);
-                       FIRInstanceIDCheckinPreferences *cachedPreferences =
-                           [self.instanceIDStore cachedCheckinPreferences];
-
-                       XCTAssertEqualObjects(cachedPreferences.deviceID, kAuthID);
-                       XCTAssertEqualObjects(cachedPreferences.secretToken, kSecret);
-                       [checkinExpectation fulfill];
-                     }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-}
-
-/**
- *  Tests that a checkin authentication ID can be removed from FIRInstanceIDStore's cache.
- */
-- (void)testRemoveCheckinPreferences {
-  XCTestExpectation *checkinExpectation = [self expectationWithDescription:@"checkin is removed"];
-  NSDictionary *plistContent = @{
-    kFIRInstanceIDDigestStringKey : @"digest-xyz",
-    kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
-  };
-  FIRInstanceIDCheckinPreferences *preferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  [preferences updateWithCheckinPlistContents:plistContent];
-
-  [self.instanceIDStore
-      saveCheckinPreferences:preferences
-                     handler:^(NSError *error) {
-                       XCTAssertNil(error);
-
-                       [self.instanceIDStore
-                           removeCheckinPreferencesWithHandler:^(NSError *_Nullable error) {
-                             XCTAssertNil(error);
-
-                             FIRInstanceIDCheckinPreferences *cachedPreferences =
-                                 [self.instanceIDStore cachedCheckinPreferences];
-                             XCTAssertNil(cachedPreferences.deviceID);
-                             XCTAssertNil(cachedPreferences.secretToken);
-                             [checkinExpectation fulfill];
-                           }];
-                     }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-}
-
-- (void)testResetCredentialsWithFreshInstall {
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID secretToken:kSecret];
-  // Expect checkin is removed if it's a fresh install.
-  [[_mockCheckinStore expect]
-      removeCheckinPreferencesWithHandler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-  // Always setting up stub after expect.
-  OCMStub([_mockCheckinStore cachedCheckinPreferences]).andReturn(checkinPreferences);
-  // Plist file doesn't exist, meaning this is a fresh install.
-  OCMStub([_mockCheckinStore hasCheckinPlist]).andReturn(NO);
-
-  [_mockInstanceIDStore resetCredentialsIfNeeded];
-  OCMVerifyAll(_mockCheckinStore);
-}
-
-- (void)testResetCredentialsWithNoCachedCheckin {
-  id niceMockCheckinStore = [OCMockObject niceMockForClass:[FIRInstanceIDCheckinStore class]];
-  [[niceMockCheckinStore reject]
-      removeCheckinPreferencesWithHandler:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
-  // Always setting up stub after expect.
-  OCMStub([_mockCheckinStore cachedCheckinPreferences]).andReturn(nil);
-
-  [_instanceIDStore resetCredentialsIfNeeded];
-  OCMVerifyAll(niceMockCheckinStore);
-}
-@end

+ 0 - 1513
Example/InstanceID/Tests/FIRInstanceIDTest.m

@@ -1,1513 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/Private/FIRInstanceID_Private.h"
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
-
-static NSString *const kFakeIID = @"12345678";
-static NSString *const kFakeAPNSToken = @"this is a fake apns token";
-static NSString *const kAuthorizedEntity = @"test-audience";
-static NSString *const kScope = @"test-scope";
-static NSString *const kToken = @"12345678:test-token";
-static FIRInstanceIDTokenInfo *sTokenInfo;
-// Faking checkin calls
-static NSString *const kDeviceAuthId = @"device-id";
-static NSString *const kSecretToken = @"secret-token";
-static NSString *const kVersionInfo = @"1.0";
-// FIRApp configuration.
-static NSString *const kGCMSenderID = @"correct_gcm_sender_id";
-static NSString *const kGoogleAppID = @"1:123:ios:123abc";
-
-@interface FIRInstanceID (ExposedForTest)
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
-@property(nonatomic, readwrite, strong) FIRInstallations *installations;
-@property(nonatomic, readwrite, copy) NSString *fcmSenderID;
-@property(nonatomic, readwrite, copy) NSString *firebaseAppID;
-@property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
-
-- (NSInteger)retryIntervalToFetchDefaultToken;
-- (BOOL)isFCMAutoInitEnabled;
-- (void)didCompleteConfigure;
-- (NSString *)cachedTokenIfAvailable;
-- (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler;
-+ (FIRInstanceID *)instanceIDForTests;
-- (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
-- (instancetype)initPrivately;
-- (void)start;
-+ (int64_t)maxRetryCountForDefaultToken;
-+ (int64_t)minIntervalForDefaultTokenRetry;
-+ (int64_t)maxRetryIntervalForDefaultTokenInSeconds;
-- (void)fetchNewTokenWithAuthorizedEntity:(NSString *)authorizedEntity
-                                    scope:(NSString *)scope
-                               instanceID:(NSString *)instanceID
-                                  options:(NSDictionary *)options
-                                  handler:(FIRInstanceIDTokenHandler)handler;
-
-@end
-
-@interface FIRInstanceIDTest : XCTestCase
-
-@property(nonatomic, readwrite, assign) BOOL hasCheckinInfo;
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-@property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
-#pragma clang diagnostic pop
-@property(nonatomic, readwrite, strong) id mockInstanceID;
-@property(nonatomic, readwrite, strong) id mockTokenManager;
-@property(nonatomic, readwrite, strong) id mockInstallations;
-@property(nonatomic, readwrite, strong) id mockAuthService;
-@property(nonatomic, readwrite, strong) id<NSObject> tokenRefreshNotificationObserver;
-
-@property(nonatomic, readwrite, copy) FIRInstanceIDTokenHandler newTokenCompletion;
-@property(nonatomic, readwrite, copy) FIRInstanceIDDeleteTokenHandler deleteTokenCompletion;
-
-@end
-
-@implementation FIRInstanceIDTest
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-- (void)setUp {
-  [super setUp];
-
-  // `+[FIRInstallations installations]` supposed to be used on `-[FIRInstanceID start]` to get
-  // `FIRInstallations` default instance. Need to stub it before.
-  self.mockInstallations = OCMClassMock([FIRInstallations class]);
-  OCMStub([self.mockInstallations installations]).andReturn(self.mockInstallations);
-
-  _instanceID = [[FIRInstanceID alloc] initPrivately];
-  [_instanceID start];
-  if (!sTokenInfo) {
-    sTokenInfo = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                    scope:kScope
-                                                                    token:kToken
-                                                               appVersion:nil
-                                                            firebaseAppID:nil];
-    sTokenInfo.cacheTime = [NSDate date];
-  }
-  [self mockInstanceIDObjects];
-}
-
-- (void)tearDown {
-  [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
-  self.mockInstanceID = nil;
-  self.instanceID = nil;
-  self.mockTokenManager = nil;
-  self.mockInstallations = nil;
-  [super tearDown];
-}
-
-- (void)mockInstanceIDObjects {
-  // Mock that we have valid checkin info. Individual tests can override this.
-  self.hasCheckinInfo = YES;
-  self.mockAuthService = OCMClassMock([FIRInstanceIDAuthService class]);
-
-  [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
-    [invocation setReturnValue:&self->_hasCheckinInfo];
-  }] hasValidCheckinInfo];
-
-  self.mockTokenManager = OCMClassMock([FIRInstanceIDTokenManager class]);
-  [[[self.mockTokenManager stub] andReturn:self.mockAuthService] authService];
-
-  _instanceID.fcmSenderID = kAuthorizedEntity;
-  self.mockInstanceID = OCMPartialMock(_instanceID);
-  [self.mockInstanceID setTokenManager:self.mockTokenManager];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  id instanceIDClassMock = OCMClassMock([FIRInstanceID class]);
-#pragma clang diagnostic pop
-
-  OCMStub(ClassMethod([instanceIDClassMock minIntervalForDefaultTokenRetry])).andReturn(2);
-  OCMStub(ClassMethod([instanceIDClassMock maxRetryIntervalForDefaultTokenInSeconds]))
-      .andReturn(10);
-}
-
-/**
- *  Tests that the FIRInstanceID's sharedInstance class method produces an instance of
- *  FIRInstanceID with an associated FIRInstanceIDTokenManager.
- */
-- (void)testSharedInstance {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  // The shared instance should be `nil` before the app is configured.
-  XCTAssertNil([FIRInstanceID instanceID]);
-
-  // The shared instance relies on the default app being configured. Configure it.
-  FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:kGoogleAppID
-                                                    GCMSenderID:kGCMSenderID];
-  options.APIKey = @"AIzaSy-ApiKeyWithValidFormat_0123456789";
-  options.projectID = @"project-id";
-  [FIRApp configureWithName:kFIRDefaultAppName options:options];
-  FIRInstanceID *instanceID = [FIRInstanceID instanceID];
-  XCTAssertNotNil(instanceID);
-  XCTAssertNotNil(instanceID.tokenManager);
-
-  // Ensure a second call returns the same instance as the first.
-  FIRInstanceID *secondInstanceID = [FIRInstanceID instanceID];
-  XCTAssertEqualObjects(instanceID, secondInstanceID);
-
-  // Reset the default app for the next test.
-  [FIRApp resetApps];
-}
-
-- (void)testFCMAutoInitEnabled {
-  XCTAssertFalse([_instanceID isFCMAutoInitEnabled],
-                 @"When FCM is not available, FCM Auto Init Enabled should be NO.");
-}
-
-- (void)testTokenShouldBeRefreshedIfCacheTokenNeedsToBeRefreshed {
-  [[[self.mockInstanceID stub] andReturn:kToken] cachedTokenIfAvailable];
-  [[[self.mockTokenManager stub] andReturnValue:@(YES)]
-      checkTokenRefreshPolicyWithIID:[OCMArg any]];
-  [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
-                                                  scope:[OCMArg any]
-                                                options:[OCMArg any]
-                                                handler:[OCMArg any]];
-  [self expectInstallationsInstallationIDWithFID:kToken error:nil];
-
-  [self.mockInstanceID didCompleteConfigure];
-  OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
-  XCTAssertEqualObjects([self.mockInstanceID token], kToken);
-}
-
-- (void)testTokenShouldBeRefreshedIfNoCacheTokenButAutoInitAllowed {
-  [[[self.mockInstanceID stub] andReturn:nil] cachedTokenIfAvailable];
-  [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
-  [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
-                                                  scope:[OCMArg any]
-                                                options:[OCMArg any]
-                                                handler:[OCMArg any]];
-
-  [self.mockInstanceID didCompleteConfigure];
-
-  OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
-}
-
-- (void)testTokenShouldBeRefreshedIfIIDAndTokenAreNotConsistent {
-  XCTestExpectation *expectation = [self expectationWithDescription:@"token request is complete"];
-  NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
-  NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
-  BOOL isSandbox = YES;
-  NSDictionary *tokenOptions = @{
-    APNSKey : fakeAPNSDeviceToken,
-    serverKey : @(isSandbox),
-  };
-  FIRInstanceIDAPNSInfo *optionsAPNSInfo =
-      [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
-  sTokenInfo.APNSInfo = optionsAPNSInfo;
-  [[[self.mockTokenManager stub] andReturn:sTokenInfo]
-      cachedTokenInfoWithAuthorizedEntity:[OCMArg any]
-                                    scope:[OCMArg any]];
-  [[self.mockTokenManager stub]
-      fetchNewTokenWithAuthorizedEntity:kGCMSenderID
-                                  scope:@"*"
-                             instanceID:@"differentIID"
-                                options:tokenOptions
-                                handler:[OCMArg invokeBlockWithArgs:@"differentIID:newToken",
-                                                                    [NSNull null], nil]];
-  [self expectInstallationsInstallationIDWithFID:@"differentIID" error:nil];
-
-  [self.mockInstanceID
-      tokenWithAuthorizedEntity:kGCMSenderID
-                          scope:@"*"
-                        options:tokenOptions
-                        handler:^(NSString *_Nullable token, NSError *_Nullable error) {
-                          XCTAssertEqualObjects(token, @"differentIID:newToken");
-                          [expectation fulfill];
-                        }];
-  [self waitForExpectationsWithTimeout:1.0 handler:NULL];
-}
-
-- (void)testTokenIsDeletedAlongWithIdentity {
-  [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
-  [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
-                                                  scope:[OCMArg any]
-                                                options:[OCMArg any]
-                                                handler:[OCMArg any]];
-
-  [self.mockInstanceID deleteIdentityWithHandler:^(NSError *_Nullable error) {
-    XCTAssertNil([self.mockInstanceID token]);
-  }];
-}
-
-- (void)testTokenIsFetchedDuringIIDGeneration {
-  XCTestExpectation *tokenExpectation = [self
-      expectationWithDescription:@"Token is refreshed when getID is called to avoid IID conflict."];
-
-  [self expectInstallationsInstallationIDWithFID:kFakeIID error:nil];
-
-  [self.mockInstanceID getIDWithHandler:^(NSString *identity, NSError *error) {
-    XCTAssertNotNil(identity);
-    XCTAssertEqual(identity, kFakeIID);
-    OCMVerify([self.mockInstanceID token]);
-    [tokenExpectation fulfill];
-  }];
-  [self waitForExpectationsWithTimeout:0.1
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Tests that when a new InstanceID token is successfully produced,
- *  the callback is invoked with a token that is not an empty string and with no error.
- */
-- (void)testNewTokenSuccess {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
-  NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
-
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
-  BOOL isSandbox = YES;
-  NSDictionary *tokenOptions = @{
-    APNSKey : fakeAPNSDeviceToken,
-    serverKey : @(isSandbox),
-  };
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 NSDictionary *options = (NSDictionary *)obj;
-                                 XCTAssertTrue([options[APNSKey] isEqual:fakeAPNSDeviceToken]);
-                                 XCTAssertTrue([options[serverKey] isEqual:@(isSandbox)]);
-                                 return YES;
-                               }]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:tokenOptions
-                                     handler:^(NSString *token, NSError *error) {
-                                       XCTAssertNotNil(token);
-                                       XCTAssertGreaterThan(token.length, 0);
-                                       XCTAssertNil(error);
-                                       [tokenExpectation fulfill];
-                                     }];
-
-  [self waitForExpectationsWithTimeout:1
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Get Token should fail if we do not have valid checkin info and are unable to
- *  retreive one.
- */
-- (void)testNewTokenCheckinFailure {
-  self.hasCheckinInfo = NO;
-
-  __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
-  [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
-    if (checkinHandler) {
-      FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
-      NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
-      checkinHandler(nil, error);
-    }
-  }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
-       return (checkinHandler = obj) != nil;
-     }]];
-
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
-  };
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:tokenOptions
-                                     handler:^(NSString *token, NSError *error) {
-                                       XCTAssertNil(token);
-                                       XCTAssertNotNil(error);
-                                       [tokenExpectation fulfill];
-                                     }];
-
-  [self waitForExpectationsWithTimeout:60.0
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Get token with no valid checkin should wait for any existing checkin operation to finish.
- *  If the checkin succeeds within a stipulated amount of time period getting the token should
- *  also succeed.
- */
-- (void)testNewTokenSuccessAfterWaiting {
-  self.hasCheckinInfo = NO;
-
-  __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
-  [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
-    if (checkinHandler) {
-      FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
-      NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
-      checkinHandler(nil, error);
-    }
-  }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
-       return (checkinHandler = obj) != nil;
-     }]];
-
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
-  };
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:tokenOptions
-                                     handler:^(NSString *token, NSError *error) {
-                                       XCTAssertNil(token);
-                                       XCTAssertNotNil(error);
-                                       [tokenExpectation fulfill];
-                                     }];
-
-  [self waitForExpectationsWithTimeout:60.0
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Test that the prod APNS token is correctly prefixed with "prod".
- */
-- (void)testAPNSTokenIsPrefixedCorrectlyForServerType {
-  NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
-  NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
-  NSDictionary *prodTokenOptions = @{
-    APNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
-    serverTypeKey : @(NO),
-  };
-
-  [[self.mockTokenManager stub]
-      fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                  scope:kScope
-                             instanceID:[OCMArg any]
-                                options:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                  NSDictionary *options = (NSDictionary *)obj;
-                                  XCTAssertTrue([options[APNSKey] hasPrefix:@"p_"]);
-                                  XCTAssertFalse([options[serverTypeKey] boolValue]);
-                                  return YES;
-                                }]
-                                handler:OCMOCK_ANY];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:prodTokenOptions
-                                     handler:^(NSString *token, NSError *error){
-                                     }];
-}
-
-/**
- *  Tests that when there is a failure in producing a new InstanceID token,
- *  the callback is invoked with an error and a nil token.
- */
-- (void)testNewTokenFailure {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = [NSDictionary dictionary];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-  [self stubInstallationsToReturnValidID];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
-    self.newTokenCompletion(nil, someError);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kScope
-                            instanceID:[OCMArg any]
-                               options:tokenOptions
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:tokenOptions
-                                     handler:^(NSString *token, NSError *error) {
-                                       XCTAssertNil(token);
-                                       XCTAssertNotNil(error);
-                                       [tokenExpectation fulfill];
-                                     }];
-
-  [self waitForExpectationsWithTimeout:1
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Tests that when a token is deleted successfully, the callback is invoked with no error.
- */
-- (void)testDeleteTokenSuccess {
-  XCTestExpectation *deleteExpectation =
-      [self expectationWithDescription:@"Delete handler invoked."];
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wnonnull"
-    self.deleteTokenCompletion(nil);
-#pragma clang diagnostic pop
-  }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                               scope:kScope
-                          instanceID:[OCMArg any]
-                             handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                               self.deleteTokenCompletion = obj;
-                               return obj != nil;
-                             }]];
-
-  [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                                             scope:kScope
-                                           handler:^(NSError *error) {
-                                             XCTAssertNil(error);
-                                             [deleteExpectation fulfill];
-                                           }];
-
-  [self waitForExpectationsWithTimeout:1
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Tests that when a token deletion fails, the callback is invoked with an error.
- */
-- (void)testDeleteTokenFailure {
-  XCTestExpectation *deleteExpectation =
-      [self expectationWithDescription:@"Delete handler invoked."];
-
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
-    self.deleteTokenCompletion(someError);
-  }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                               scope:kScope
-                          instanceID:[OCMArg any]
-                             handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                               self.deleteTokenCompletion = obj;
-                               return obj != nil;
-                             }]];
-
-  [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                                             scope:kScope
-                                           handler:^(NSError *error) {
-                                             XCTAssertNotNil(error);
-                                             [deleteExpectation fulfill];
-                                           }];
-
-  [self waitForExpectationsWithTimeout:1
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Tests that not having a senderID will fetch a `nil` default token.
- */
-- (void)testDefaultToken_noSenderID {
-  _instanceID.fcmSenderID = nil;
-  XCTAssertNil([self.mockInstanceID token]);
-}
-
-/**
- *  Tests that not having a cached token results in trying to fetch a new default token.
- */
-- (void)testDefaultToken_noCachedToken {
-  [[[self.mockTokenManager stub] andReturn:nil]
-      cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                    scope:@"*"];
-
-  OCMExpect([self.mockInstanceID defaultTokenWithHandler:nil]);
-  XCTAssertNil([self.mockInstanceID token]);
-  OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
-  [self.mockInstanceID stopMocking];
-}
-
-/**
- *  Tests that when we have a cached default token, calling `getToken` returns that token
- *  without hitting the network.
- */
-- (void)testDefaultToken_validCachedToken {
-  [[[self.mockTokenManager stub] andReturn:sTokenInfo]
-      cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                    scope:@"*"];
-  [[self.mockInstanceID reject] defaultTokenWithHandler:nil];
-  XCTAssertEqualObjects([self.mockInstanceID token], kToken);
-}
-
-/**
- *  Tests that the callback handler will be invoked when the default token is fetched
- *  despite the token being unchanged.
- */
-- (void)testDefaultToken_callbackInvokedForUnchangedToken {
-  XCTestExpectation *defaultTokenExpectation =
-      [self expectationWithDescription:@"Token fetch was successful."];
-
-  __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Mock Token manager to always succeed the token fetch, and return
-  // a particular cached value.
-
-  // Return a dynamic cachedToken variable whenever the cached is checked.
-  // This uses an invocation-based mock because the |cachedToken| pointer
-  // will change. Normal stubbing will always return the initial pointer,
-  // which in this case is 0x0 (nil).
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
-    [invocation setReturnValue:&tokenInfo];
-  }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  __block NSString *notificationToken = nil;
-
-  // Fetch token once to store token state
-  NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
-  self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
-      addObserverForName:notificationName
-                  object:nil
-                   queue:nil
-              usingBlock:^(NSNotification *_Nonnull note) {
-                // Should have saved token to cache
-                cachedTokenInfo = sTokenInfo;
-                notificationToken = [[self.instanceID token] copy];
-                [defaultTokenExpectation fulfill];
-              }];
-  XCTAssertNil([self.mockInstanceID token]);
-  [self waitForExpectationsWithTimeout:10.0 handler:nil];
-  [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
-
-  XCTAssertEqualObjects(notificationToken, kToken);
-
-  // Fetch default handler again without any token changes
-  XCTestExpectation *tokenCallback = [self expectationWithDescription:@"Callback was invoked."];
-
-  [self.mockInstanceID defaultTokenWithHandler:^(NSString *token, NSError *error) {
-    notificationToken = token;
-    [tokenCallback fulfill];
-  }];
-  [self waitForExpectationsWithTimeout:10.0 handler:nil];
-  XCTAssertEqualObjects(notificationToken, kToken);
-}
-
-/**
- *  Test that when we fetch a new default token and cache it successfully we post a
- *  tokenRefresh notification which allows to fetch the cached token.
- */
-- (void)testDefaultTokenFetch_returnValidToken {
-  XCTestExpectation *defaultTokenExpectation =
-      [self expectationWithDescription:@"Successfully got default token."];
-
-  __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Mock Token manager to always succeed the token fetch, and return
-  // a particular cached value.
-
-  // Return a dynamic cachedToken variable whenever the cached is checked.
-  // This uses an invocation-based mock because the |cachedToken| pointer
-  // will change. Normal stubbing will always return the initial pointer,
-  // which in this case is 0x0 (nil).
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
-    [invocation setReturnValue:&tokenInfo];
-  }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  __block NSString *notificationToken = nil;
-
-  NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
-  self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
-      addObserverForName:notificationName
-                  object:nil
-                   queue:nil
-              usingBlock:^(NSNotification *_Nonnull note) {
-                // Should have saved token to cache
-                cachedTokenInfo = sTokenInfo;
-
-                notificationToken = [[self.instanceID token] copy];
-                [defaultTokenExpectation fulfill];
-              }];
-  XCTAssertNil([self.mockInstanceID token]);
-  [self waitForExpectationsWithTimeout:10.0 handler:nil];
-  [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
-
-  XCTAssertEqualObjects(notificationToken, kToken);
-}
-
-/**
- *  Tests that if we fail to fetch the token from the server for the first time we retry again
- *  later with exponential backoff unless we succeed.
- */
-- (void)testDefaultTokenFetch_retryFetchToken {
-  const int trialsBeforeSuccess = 3;
-  __block int newTokenFetchCount = 0;
-  __block int64_t lastFetchTimestampInSeconds;
-
-  XCTestExpectation *defaultTokenExpectation =
-      [self expectationWithDescription:@"Successfully got default token."];
-
-  __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Mock Token manager.
-  // Return a dynamic cachedToken variable whenever the cached is checked.
-  // This uses an invocation-based mock because the |cachedToken| pointer
-  // will change. Normal stubbing will always return the initial pointer,
-  // which in this case is 0x0 (nil).
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
-    [invocation setReturnValue:&tokenInfo];
-  }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    newTokenFetchCount++;
-    int64_t delaySinceLastFetchInSeconds =
-        FIRInstanceIDCurrentTimestampInSeconds() - lastFetchTimestampInSeconds;
-    // Test exponential backoff.
-    if (newTokenFetchCount > 1) {
-      XCTAssertLessThanOrEqual(1 << (newTokenFetchCount - 1), delaySinceLastFetchInSeconds);
-    }
-    lastFetchTimestampInSeconds = FIRInstanceIDCurrentTimestampInSeconds();
-
-    if (newTokenFetchCount < trialsBeforeSuccess) {
-      NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
-      self.newTokenCompletion(nil, error);
-    } else {
-      self.newTokenCompletion(kToken, nil);
-    }
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  __block int notificationPostCount = 0;
-  __block NSString *notificationToken = nil;
-
-  NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
-
-  self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
-      addObserverForName:notificationName
-                  object:nil
-                   queue:nil
-              usingBlock:^(NSNotification *_Nonnull note) {
-                // Should have saved token to cache
-                cachedTokenInfo = sTokenInfo;
-
-                notificationPostCount++;
-                notificationToken = [[self.instanceID token] copy];
-                [defaultTokenExpectation fulfill];
-              }];
-  XCTAssertNil([self.mockInstanceID token]);
-
-  [self waitForExpectationsWithTimeout:20.0 handler:nil];
-  [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
-
-  XCTAssertEqualObjects(notificationToken, kToken);
-  XCTAssertEqual(notificationPostCount, 1);
-  XCTAssertEqual(newTokenFetchCount, trialsBeforeSuccess);
-}
-
-/**
- *  Tests that when we don't have a cached default token multiple invocations to `getToken`
- *  lead to a single networking call to fetch the token. Also verify that we post one unique
- *  TokenRefresh notification for multiple invocations.
- */
-- (void)testDefaultToken_multipleInvocations {
-  __block int newTokenFetchCount = 0;
-  XCTestExpectation *defaultTokenExpectation =
-      [self expectationWithDescription:@"Successfully got default token."];
-
-  __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Mock Token manager.
-  // Return a dynamic cachedToken variable whenever the cached is checked.
-  // This uses an invocation-based mock because the |cachedToken| pointer
-  // will change. Normal stubbing will always return the initial pointer,
-  // which in this case is 0x0 (nil).
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
-    [invocation setReturnValue:&tokenInfo];
-  }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    // Invoke callback after some delay (network delay)
-    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
-                   dispatch_get_main_queue(), ^{
-                     self.newTokenCompletion(kToken, nil);
-                   });
-    newTokenFetchCount++;
-    XCTAssertEqual(newTokenFetchCount, 1);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  __block int notificationPostCount = 0;
-  __block NSString *notificationToken = nil;
-  NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
-  self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
-      addObserverForName:notificationName
-                  object:nil
-                   queue:nil
-              usingBlock:^(NSNotification *_Nonnull note) {
-                // Should have saved token to cache
-                cachedTokenInfo = sTokenInfo;
-
-                notificationPostCount++;
-                notificationToken = [[self.instanceID token] copy];
-                [defaultTokenExpectation fulfill];
-              }];
-
-  XCTAssertNil([self.mockInstanceID token]);
-  // Invoke get token again with some delay. Our initial request to getToken hasn't yet
-  // returned from the server.
-  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
-                 dispatch_get_main_queue(), ^{
-                   XCTAssertNil([self.mockInstanceID token]);
-                 });
-  // Invoke again after further delay.
-  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
-                 dispatch_get_main_queue(), ^{
-                   XCTAssertNil([self.mockInstanceID token]);
-                 });
-
-  [self waitForExpectationsWithTimeout:15.0 handler:nil];
-  [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
-
-  XCTAssertEqualObjects(notificationToken, kToken);
-  XCTAssertEqual(notificationPostCount, 1);
-  XCTAssertEqual(newTokenFetchCount, 1);
-}
-
-- (void)testDefaultToken_maxRetries {
-  __block int newTokenFetchCount = 0;
-  XCTestExpectation *defaultTokenExpectation =
-      [self expectationWithDescription:@"Did retry maximum times to fetch default token."];
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Mock Token manager.
-  [[[self.mockTokenManager stub] andReturn:nil]
-      cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                    scope:kFIRInstanceIDDefaultTokenScope];
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    newTokenFetchCount++;
-    NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeNetwork];
-    self.newTokenCompletion(nil, error);
-    if (newTokenFetchCount == [FIRInstanceID maxRetryCountForDefaultToken]) {
-      [defaultTokenExpectation fulfill];
-    }
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  // Mock Instance ID's retry interval to 0, to vastly speed up this test.
-  [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
-
-  // Try to fetch token once. It should set off retries since we mock failure.
-  XCTAssertNil([self.mockInstanceID token]);
-
-  [self waitForExpectationsWithTimeout:1.0 handler:nil];
-
-  XCTAssertEqual(newTokenFetchCount, [FIRInstanceID maxRetryCountForDefaultToken]);
-}
-
-- (void)testInstanceIDWithHandler_WhileRequesting_Success {
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
-  XCTestExpectation *fetchNewTokenExpectation =
-      [self expectationWithDescription:@"fetchNewTokenExpectation"];
-  __block FIRInstanceIDTokenHandler tokenHandler;
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __unsafe_unretained FIRInstanceIDTokenHandler handler;
-    [invocation getArgument:&handler atIndex:6];
-    tokenHandler = handler;
-    [fetchNewTokenExpectation fulfill];
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg any]];
-
-  // Make 1st call
-  XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler1 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation1 fulfill];
-        XCTAssertNotNil(result);
-        XCTAssertEqual(result.token, kToken);
-        XCTAssertNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler1];
-
-  // Make 2nd call
-  XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler2 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation2 fulfill];
-        XCTAssertNotNil(result);
-        XCTAssertEqual(result.token, kToken);
-        XCTAssertNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler2];
-
-  // Wait for `fetchNewTokenWithAuthorizedEntity` to be performed
-  [self waitForExpectations:@[ fetchNewTokenExpectation ] timeout:1 enforceOrder:false];
-  // Finish token fetch request
-  tokenHandler(kToken, nil);
-
-  // Wait for completion handlers for both calls to be performed
-  [self waitForExpectationsWithTimeout:1 handler:NULL];
-}
-
-- (void)testInstanceIDWithHandler_WhileRequesting_RetrySuccess {
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Expect `fetchNewTokenWithAuthorizedEntity` to be called twice
-  XCTestExpectation *fetchNewTokenExpectation1 =
-      [self expectationWithDescription:@"fetchNewTokenExpectation1"];
-  XCTestExpectation *fetchNewTokenExpectation2 =
-      [self expectationWithDescription:@"fetchNewTokenExpectation2"];
-  NSArray *fetchNewTokenExpectations = @[ fetchNewTokenExpectation1, fetchNewTokenExpectation2 ];
-
-  __block NSInteger fetchNewTokenCallCount = 0;
-  __block FIRInstanceIDTokenHandler tokenHandler;
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __unsafe_unretained FIRInstanceIDTokenHandler handler;
-    [invocation getArgument:&handler atIndex:6];
-    tokenHandler = handler;
-    [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
-    fetchNewTokenCallCount += 1;
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg any]];
-
-  // Mock Instance ID's retry interval to 0, to vastly speed up this test.
-  [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
-
-  // Make 1st call
-  XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler1 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation1 fulfill];
-        XCTAssertNotNil(result);
-        XCTAssertEqual(result.token, kToken);
-        XCTAssertNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler1];
-
-  // Make 2nd call
-  XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler2 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation2 fulfill];
-        XCTAssertNotNil(result);
-        XCTAssertEqual(result.token, kToken);
-        XCTAssertNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler2];
-
-  // Wait for the 1st `fetchNewTokenWithAuthorizedEntity` to be performed
-  [self waitForExpectations:@[ fetchNewTokenExpectation1 ] timeout:1 enforceOrder:false];
-  // Fail for the 1st time
-  tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
-
-  // Wait for the 2nd token feth
-  [self waitForExpectations:@[ fetchNewTokenExpectation2 ] timeout:1 enforceOrder:false];
-  // Finish with success
-  tokenHandler(kToken, nil);
-
-  // Wait for completion handlers for both calls to be performed
-  [self waitForExpectationsWithTimeout:1 handler:NULL];
-}
-
-- (void)testInstanceIDWithHandler_WhileRequesting_RetryFailure {
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
-  NSMutableArray<XCTestExpectation *> *fetchNewTokenExpectations = [NSMutableArray array];
-  for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
-    NSString *name = [NSString stringWithFormat:@"fetchNewTokenExpectation-%ld", (long)i];
-    [fetchNewTokenExpectations addObject:[self expectationWithDescription:name]];
-  }
-
-  __block NSInteger fetchNewTokenCallCount = 0;
-  __block FIRInstanceIDTokenHandler tokenHandler;
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __unsafe_unretained FIRInstanceIDTokenHandler handler;
-    [invocation getArgument:&handler atIndex:6];
-    tokenHandler = handler;
-    [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
-    fetchNewTokenCallCount += 1;
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg any]];
-
-  // Mock Instance ID's retry interval to 0, to vastly speed up this test.
-  [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
-
-  // Make 1st call
-  XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler1 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation1 fulfill];
-        XCTAssertNil(result);
-        XCTAssertNotNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler1];
-
-  // Make 2nd call
-  XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
-  FIRInstanceIDResultHandler handler2 =
-      ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
-        [handlerExpectation2 fulfill];
-        XCTAssertNil(result);
-        XCTAssertNotNil(error);
-      };
-
-  [self.mockInstanceID instanceIDWithHandler:handler2];
-
-  for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
-    // Wait for the i `fetchNewTokenWithAuthorizedEntity` to be performed
-    [self waitForExpectations:@[ fetchNewTokenExpectations[i] ] timeout:1 enforceOrder:false];
-    // Fail for the i time
-    tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
-  }
-
-  // Wait for completion handlers for both calls to be performed
-  [self waitForExpectationsWithTimeout:1 handler:NULL];
-}
-
-/**
- *  Tests a Keychain read failure while we try to fetch a new InstanceID token. If the Keychain
- *  read fails we won't be able to fetch the public key which is required while fetching a new
- *  token. In such a case we should return KeyPair failure.
- */
-- (void)testNewTokenFetch_keyChainError {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // Simulate keypair fetch/generation failure.
-  NSError *installationIDError = [NSError errorWithDomain:@"Test" code:-1 userInfo:nil];
-  [self expectInstallationsInstallationIDWithFID:nil error:installationIDError];
-
-  [[self.mockTokenManager reject] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                                              scope:kScope
-                                                         instanceID:[OCMArg any]
-                                                            options:[OCMArg any]
-                                                            handler:[OCMArg any]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:nil
-                                     handler:^(NSString *token, NSError *error) {
-                                       XCTAssertNil(token);
-                                       XCTAssertNotNil(error);
-                                       [tokenExpectation fulfill];
-                                     }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-  OCMVerifyAll(self.mockTokenManager);
-}
-
-/**
- *  If a token fetch includes in its options an "apns_token" object, but not a "apns_sandbox" key,
- *  ensure that an "apns_sandbox" key is added to the token options (via automatic detection).
- */
-- (void)testTokenFetchAPNSServerTypeIsIncludedIfAPNSTokenProvided {
-  XCTestExpectation *apnsServerTypeExpectation =
-      [self expectationWithDescription:@"apns_sandbox key was included in token options"];
-
-  [self stubInstallationsToReturnValidID];
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  NSData *apnsToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
-  // Option is purposefully missing the apns_sandbox key
-  NSDictionary *tokenOptions = @{kFIRInstanceIDTokenOptionsAPNSKey : apnsToken};
-
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    // Inspect
-    __unsafe_unretained NSDictionary *options;
-    [invocation getArgument:&options atIndex:5];
-    if (options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] != nil) {
-      [apnsServerTypeExpectation fulfill];
-    }
-    self.newTokenCompletion(kToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
-                                       scope:kScope
-                                     options:tokenOptions
-                                     handler:^(NSString *token, NSError *error){
-                                     }];
-
-  [self waitForExpectationsWithTimeout:60.0
-                               handler:^(NSError *error) {
-                                 XCTAssertNil(error);
-                               }];
-}
-
-/**
- *  Tests that if a token was fetched, but during the fetch the APNs data was set, that a new
- *  token is fetched to associate the APNs data, and is not returned from the cache.
- */
-- (void)testTokenFetch_ignoresCacheIfAPNSInfoDifferent {
-  XCTestExpectation *tokenRequestExpectation =
-      [self expectationWithDescription:@"Token was fetched from the network"];
-
-  // Initialize a token in the cache *WITHOUT* APNSInfo
-  // This token is |kToken|, but we will simulate that a fetch will return another token
-  NSString *oldCachedToken = kToken;
-  NSString *fetchedToken = @"abcd123_newtoken";
-
-  [self stubInstallationsToReturnValidID];
-
-  [self mockAuthServiceToAlwaysReturnValidCheckin];
-
-  // During this test use the default scope ("*") to simulate the default token behavior.
-
-  // Return a dynamic cachedToken variable whenever the cached is checked.
-  // This uses an invocation-based mock because the |cachedToken| pointer
-  // will change. Normal stubbing will always return the initial pointer,
-  // which in this case is 0x0 (nil).
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    __autoreleasing FIRInstanceIDTokenInfo *tokenInfo =
-        [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                           scope:kFIRInstanceIDDefaultTokenScope
-                                                           token:oldCachedToken
-                                                      appVersion:@"1.0"
-                                                   firebaseAppID:@"firebaseAppID"];
-    [invocation setReturnValue:&tokenInfo];
-  }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
-
-  // Mock the network request to return |fetchedToken|, so we can clearly see if the token is
-  // is different than what was cached.
-  [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
-    [tokenRequestExpectation fulfill];
-    self.newTokenCompletion(fetchedToken, nil);
-  }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                 scope:kFIRInstanceIDDefaultTokenScope
-                            instanceID:[OCMArg any]
-                               options:[OCMArg any]
-                               handler:[OCMArg checkWithBlock:^BOOL(id obj) {
-                                 self.newTokenCompletion = obj;
-                                 return obj != nil;
-                               }]];
-
-  // Begin request
-  // Token options has APNS data, which is not associated with the cached token
-  NSDictionary *tokenOptions = @{
-    kFIRInstanceIDTokenOptionsAPNSKey : [@"apns" dataUsingEncoding:NSUTF8StringEncoding],
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(NO)
-  };
-  [self.instanceID
-      tokenWithAuthorizedEntity:kAuthorizedEntity
-                          scope:kFIRInstanceIDDefaultTokenScope
-                        options:tokenOptions
-                        handler:^(NSString *_Nullable token, NSError *_Nullable error) {
-                          XCTAssertEqualObjects(token, fetchedToken);
-                        }];
-
-  [self waitForExpectationsWithTimeout:0.5 handler:nil];
-}
-
-/**
- *  Tests that if there is a keychain failure while fetching the InstanceID of the token we should
- *  return nil for the identity.
- */
-- (void)testInstanceIDFetch_keyChainError {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"InstanceID fetch handler invoked."];
-
-  // Simulate keypair fetch/generation failure.
-  NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
-  [self expectInstallationsInstallationIDWithFID:nil error:error];
-
-  [self.instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
-    XCTAssertNil(identity);
-    XCTAssertNotNil(error);
-    [tokenExpectation fulfill];
-  }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-}
-
-- (void)testInstanceIDDeleteSuccess {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
-
-  NSString *instanceID = @"validID";
-  [self expectInstallationsInstallationIDWithFID:instanceID error:nil];
-  [self expectTokenManagerDeleteAllTokensWithIID:instanceID completeWithError:nil];
-  [self expectTokenManagerDeleteAllTokensLocallyWithError:nil];
-  [self expectInstallationsDeleteWithError:nil];
-  [self expectAuthServiceResetCheckinWithError:nil];
-
-  [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
-    XCTAssertNil(error);
-    [tokenExpectation fulfill];
-  }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-
-  OCMVerifyAll(self.mockInstallations);
-  OCMVerifyAll(self.mockTokenManager);
-}
-
-- (void)testInstanceIDDelete_keyChainError {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
-
-  NSString *instanceID = @"validID";
-  [self expectInstallationsInstallationIDWithFID:instanceID error:nil];
-  [self expectTokenManagerDeleteAllTokensWithIID:instanceID completeWithError:nil];
-  [self expectTokenManagerDeleteAllTokensLocallyWithError:nil];
-  [self expectAuthServiceResetCheckinWithError:nil];
-
-  // Simulate keychain fetch/generation failure.
-  NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
-  [self expectInstallationsDeleteWithError:error];
-
-  [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
-    XCTAssertNotNil(error);
-    [tokenExpectation fulfill];
-  }];
-
-  [self waitForExpectationsWithTimeout:1 handler:nil];
-
-  OCMVerifyAll(self.mockInstallations);
-  OCMVerifyAll(self.mockTokenManager);
-}
-
-- (void)testRefreshDifferentTokenFromMessaging {
-  _instanceID.defaultFCMToken = kToken;
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
-  NSString *newTokenFromMessaging = @"a_new_token_from_messaging";
-  FIRInstanceIDTokenInfo *cachedTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kFIRInstanceIDDefaultTokenScope
-                                                         token:kToken
-                                                    appVersion:@""
-                                                 firebaseAppID:kGoogleAppID];
-  OCMStub([self.mockTokenManager
-              cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                            scope:kFIRInstanceIDDefaultTokenScope])
-      .andReturn(cachedTokenInfo);
-
-  OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
-                                        withOptions:[OCMArg any]]);
-  [[NSNotificationCenter defaultCenter]
-      postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
-                    object:newTokenFromMessaging];
-  OCMVerifyAll(self.mockTokenManager);
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
-}
-
-- (void)testRefreshTheSameTokenFromMessaging {
-  _instanceID.defaultFCMToken = kToken;
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
-
-  NSString *newTokenFromMessaging = kToken;
-  FIRInstanceIDTokenInfo *cachedTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kFIRInstanceIDDefaultTokenScope
-                                                         token:kToken
-                                                    appVersion:@""
-                                                 firebaseAppID:kGoogleAppID];
-  OCMStub([self.mockTokenManager
-              cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                            scope:kFIRInstanceIDDefaultTokenScope])
-      .andReturn(cachedTokenInfo);
-
-  OCMReject([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
-                                        withOptions:[OCMArg any]]);
-  [[NSNotificationCenter defaultCenter]
-      postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
-                    object:newTokenFromMessaging];
-  OCMVerifyAll(self.mockTokenManager);
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
-}
-
-- (void)testRefreshDifferentTokenInInstanceIDStorage {
-  _instanceID.defaultFCMToken = kToken;
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
-  // New token from messaging is the same as local cache in InstanceID
-  // But the token in InstanceID storage is different
-  NSString *newTokenFromMessaging = kToken;
-
-  FIRInstanceIDTokenInfo *cachedTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kFIRInstanceIDDefaultTokenScope
-                                                         token:@"a_outdated_token_in_storage"
-                                                    appVersion:@""
-                                                 firebaseAppID:kGoogleAppID];
-  OCMStub([self.mockTokenManager
-              cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                            scope:kFIRInstanceIDDefaultTokenScope])
-      .andReturn(cachedTokenInfo);
-
-  OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
-                                        withOptions:[OCMArg any]]);
-  [[NSNotificationCenter defaultCenter]
-      postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
-                    object:newTokenFromMessaging];
-  OCMVerifyAll(self.mockTokenManager);
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
-}
-
-- (void)testRefreshNullTokenFromMessaging {
-  _instanceID.defaultFCMToken = kToken;
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
-  // New token from messaging is the same as local cache in InstanceID
-  // But the token in InstanceID storage is different
-  NSString *newTokenFromMessaging = nil;
-
-  FIRInstanceIDTokenInfo *cachedTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kFIRInstanceIDDefaultTokenScope
-                                                         token:kToken
-                                                    appVersion:@""
-                                                 firebaseAppID:kGoogleAppID];
-  OCMStub([self.mockTokenManager
-              cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
-                                            scope:kFIRInstanceIDDefaultTokenScope])
-      .andReturn(cachedTokenInfo);
-
-  OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
-                                        withOptions:[OCMArg any]]);
-  [[NSNotificationCenter defaultCenter]
-      postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
-                    object:newTokenFromMessaging];
-  OCMVerifyAll(self.mockTokenManager);
-  XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
-}
-
-#pragma mark - Private Helpers
-
-- (void)stubInstallationsToReturnValidID {
-  OCMStub([self.mockInstallations
-      installationIDWithCompletion:[OCMArg
-                                       checkWithBlock:^BOOL(FIRInstallationsIDHandler completion) {
-                                         completion(@"validID", nil);
-                                         return YES;
-                                       }]]);
-}
-
-- (FIRInstanceIDCheckinPreferences *)validCheckinPreferences {
-  NSDictionary *gservicesData = @{
-    kFIRInstanceIDVersionInfoStringKey : kVersionInfo,
-    kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
-  };
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
-                                                    secretToken:kSecretToken];
-  [checkinPreferences updateWithCheckinPlistContents:gservicesData];
-  return checkinPreferences;
-}
-
-- (void)mockAuthServiceToAlwaysReturnValidCheckin {
-  FIRInstanceIDCheckinPreferences *validCheckin = [self validCheckinPreferences];
-  __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
-  [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
-    if (checkinHandler) {
-      checkinHandler(validCheckin, nil);
-    }
-  }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
-       return (checkinHandler = obj) != nil;
-     }]];
-}
-
-- (void)expectInstallationsInstallationIDWithFID:(nullable NSString *)FID
-                                           error:(nullable NSError *)error {
-  OCMExpect([self.mockInstallations
-      installationIDWithCompletion:[OCMArg
-                                       checkWithBlock:^BOOL(FIRInstallationsIDHandler completion) {
-                                         completion(FID, error);
-                                         return YES;
-                                       }]]);
-}
-
-- (void)expectInstallationsDeleteWithError:(nullable NSError *)deletionError {
-  OCMExpect([self.mockInstallations
-      deleteWithCompletion:[self errorCompletionOCMArgCompletingWithError:deletionError]]);
-}
-
-- (void)expectTokenManagerDeleteAllTokensWithIID:(NSString *)identifier
-                               completeWithError:(nullable NSError *)error {
-  OCMExpect([self.mockTokenManager
-      deleteAllTokensWithInstanceID:identifier
-                            handler:[self errorCompletionOCMArgCompletingWithError:error]]);
-}
-
-- (void)expectTokenManagerDeleteAllTokensLocallyWithError:(nullable NSError *)error {
-  OCMExpect([self.mockTokenManager
-      deleteAllTokensLocallyWithHandler:[self errorCompletionOCMArgCompletingWithError:error]]);
-}
-
-- (void)expectAuthServiceResetCheckinWithError:(NSError *)error {
-  OCMStub([self.mockAuthService
-      resetCheckinWithHandler:[self errorCompletionOCMArgCompletingWithError:error]]);
-}
-
-- (id)errorCompletionOCMArgCompletingWithError:(NSError *)errorToComplete {
-  return [OCMArg checkWithBlock:^BOOL(void (^completion)(NSError *)) {
-    completion(errorToComplete);
-    return YES;
-  }];
-}
-#pragma clang diagnostic pop
-
-@end

+ 0 - 196
Example/InstanceID/Tests/FIRInstanceIDTokenInfoTest.m

@@ -1,196 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDAPNSInfo.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-
-static NSString *const kAuthorizedEntity = @"authorizedEntity";
-static NSString *const kScope = @"scope";
-static NSString *const kToken = @"eMP633ZkDYA:APA91bGfnlnbinRVE7nUwJSr_k6cuSTKectOlt66dKv1r_-"
-                                @"9Qvhy9XljAI62QPw307rgA0MaFHPnrU5sFxGZvsncRnkfuciwTUeyRpPNDZMFhNXt"
-                                @"7h1BKq9Wb2A0LAANpQefrPHVUp4p";
-static NSString *const kFirebaseAppID = @"firebaseAppID";
-static NSString *const kIID = @"eMP633ZkDYA";
-static BOOL const kAPNSSandbox = NO;
-
-@interface FIRInstanceIDTokenInfoTest : XCTestCase
-
-@property(nonatomic, strong) NSData *APNSDeviceToken;
-@property(nonatomic, strong) FIRInstanceIDTokenInfo *validTokenInfo;
-@property(nonatomic, strong) id mockOptions;
-
-@end
-
-@implementation FIRInstanceIDTokenInfoTest
-
-- (void)setUp {
-  [super setUp];
-
-  self.APNSDeviceToken = [@"validDeviceToken" dataUsingEncoding:NSUTF8StringEncoding];
-
-  self.mockOptions = OCMClassMock([FIROptions class]);
-  OCMStub([self.mockOptions defaultOptionsDictionary]).andReturn(@{
-    kFIRGoogleAppID : kFirebaseAppID
-  });
-
-  self.validTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken
-                                                    appVersion:FIRInstanceIDCurrentAppVersion()
-                                                 firebaseAppID:FIRInstanceIDFirebaseAppID()];
-  self.validTokenInfo.APNSInfo =
-      [[FIRInstanceIDAPNSInfo alloc] initWithDeviceToken:self.APNSDeviceToken
-                                               isSandbox:kAPNSSandbox];
-  self.validTokenInfo.cacheTime = [NSDate date];
-}
-
-- (void)tearDown {
-  [self.mockOptions stopMocking];
-  [super tearDown];
-}
-
-- (void)testTokenInfoCreationWithInvalidArchive {
-  NSData *badData = [@"badData" dataUsingEncoding:NSUTF8StringEncoding];
-  FIRInstanceIDTokenInfo *info = nil;
-  @try {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-    info = [NSKeyedUnarchiver unarchiveObjectWithData:badData];
-#pragma clang diagnostic pop
-  } @catch (NSException *e) {
-    XCTAssertEqualObjects([e name], @"NSInvalidArgumentException");
-  }
-  XCTAssertNil(info);
-}
-
-// Test that archiving a FIRInstanceIDTokenInfo object and restoring it from the archive
-// yields the same values for all the fields.
-- (void)testTokenInfoEncodingAndDecoding {
-  FIRInstanceIDTokenInfo *info = self.validTokenInfo;
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:info];
-  FIRInstanceIDTokenInfo *restoredInfo = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
-#pragma clang diagnostic pop
-  XCTAssertEqualObjects(restoredInfo.authorizedEntity, info.authorizedEntity);
-  XCTAssertEqualObjects(restoredInfo.scope, info.scope);
-  XCTAssertEqualObjects(restoredInfo.token, info.token);
-  XCTAssertEqualObjects(restoredInfo.appVersion, info.appVersion);
-  XCTAssertEqualObjects(restoredInfo.firebaseAppID, info.firebaseAppID);
-  XCTAssertEqualObjects(restoredInfo.cacheTime, info.cacheTime);
-  XCTAssertEqualObjects(restoredInfo.APNSInfo.deviceToken, info.APNSInfo.deviceToken);
-  XCTAssertEqual(restoredInfo.APNSInfo.sandbox, info.APNSInfo.sandbox);
-}
-
-// Test that archiving a FIRInstanceIDTokenInfo object with missing fields and restoring it
-// from the archive yields the same values for all the fields.
-- (void)testTokenInfoEncodingAndDecodingWithMissingFields {
-  // Don't include appVersion, firebaseAppID, APNSInfo and cacheTime
-  FIRInstanceIDTokenInfo *sparseInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken
-                                                    appVersion:nil
-                                                 firebaseAppID:nil];
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-  NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:sparseInfo];
-  FIRInstanceIDTokenInfo *restoredInfo = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
-#pragma clang diagnostic pop
-  XCTAssertEqualObjects(restoredInfo.authorizedEntity, sparseInfo.authorizedEntity);
-  XCTAssertEqualObjects(restoredInfo.scope, sparseInfo.scope);
-  XCTAssertEqualObjects(restoredInfo.token, sparseInfo.token);
-  XCTAssertNil(restoredInfo.appVersion);
-  XCTAssertNil(restoredInfo.firebaseAppID);
-  XCTAssertNil(restoredInfo.cacheTime);
-  XCTAssertNil(restoredInfo.APNSInfo);
-}
-
-- (void)testTokenFreshnessWithLocaleChange {
-  // Default should be fresh because we mock last fetch token time just now.
-  XCTAssertTrue([self.validTokenInfo isFreshWithIID:kIID]);
-
-  // Locale change should affect token refreshness.
-  // Set to a different locale than the current locale.
-  [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hant"
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  [[NSUserDefaults standardUserDefaults] synchronize];
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-  // Reset locale
-  [[NSUserDefaults standardUserDefaults] setObject:FIRInstanceIDCurrentLocale()
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  [[NSUserDefaults standardUserDefaults] synchronize];
-}
-
-- (void)testTokenFreshnessWithTokenTimestampChange {
-  XCTAssertTrue([self.validTokenInfo isFreshWithIID:kIID]);
-  // Set last fetch token time 7 days ago.
-  NSTimeInterval lastFetchTokenTimestamp =
-      FIRInstanceIDCurrentTimestampInSeconds() - 7 * 24 * 60 * 60;
-  self.validTokenInfo.cacheTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTokenTimestamp];
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-
-  // Set last fetch token time more than 7 days ago.
-  lastFetchTokenTimestamp = FIRInstanceIDCurrentTimestampInSeconds() - 8 * 24 * 60 * 60;
-  self.validTokenInfo.cacheTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTokenTimestamp];
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-
-  // Set last fetch token time nil to mock legacy storage format. Token should be considered not
-  // fresh.
-  self.validTokenInfo.cacheTime = nil;
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-}
-
-- (void)testTokenFreshnessWithFirebaseAppIDChange {
-  XCTAssertTrue([self.validTokenInfo isFreshWithIID:kIID]);
-  // Change Firebase App ID.
-  [FIROptions defaultOptions].googleAppID = @"newFirebaseAppID:ios:abcdefg";
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-}
-
-- (void)testTokenFreshnessWithAppVersionChange {
-  XCTAssertTrue([self.validTokenInfo isFreshWithIID:kIID]);
-  // Change app version.
-  self.validTokenInfo =
-      [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                         scope:kScope
-                                                         token:kToken
-                                                    appVersion:@"1.1"
-                                                 firebaseAppID:FIRInstanceIDFirebaseAppID()];
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-}
-
-- (void)testTokenInconsistentWithIID {
-  XCTAssertTrue([self.validTokenInfo isFreshWithIID:kIID]);
-  // Change token.
-  self.validTokenInfo = [[FIRInstanceIDTokenInfo alloc]
-      initWithAuthorizedEntity:kAuthorizedEntity
-                         scope:kScope
-                         token:@"cxhhwVY27AE:APA91bGfnlnbinRVE7nUwJSr_k6cuSTKectOlt66dKv1r_-"
-                               @"9Qvhy9XljAI62QPw307rgA0MaFHPnrU5sFxGZvsncRnkfuciwTUeyRpPNDZMFhNXt7"
-                               @"h1BKq9Wb2A0LAANpQefrPHVUp4p"
-                    appVersion:@"1.1"
-                 firebaseAppID:FIRInstanceIDFirebaseAppID()];
-  XCTAssertFalse([self.validTokenInfo isFreshWithIID:kIID]);
-}
-@end

+ 0 - 44
Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.h

@@ -1,44 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation.h"
-
-@class FIRInstanceIDBackupExcludedPlist;
-@class FIRInstanceIDCheckinPreferences;
-@class FIRInstanceIDCheckinStore;
-@class FIRInstanceIDTokenDeleteOperation;
-@class FIRInstanceIDTokenFetchOperation;
-@class FIRInstanceIDTokenStore;
-
-@interface FIRInstanceIDTokenManager (Test) <FIRInstanceIDStoreDelegate>
-
-@property(nonatomic, readonly, strong) FIRInstanceIDStore *instanceIDStore;
-
-/**
- *  Create a InstanceID store with specific backup excluded plist and checkin store.
- *
- *  @param checkinStore The persistent store used to save checkin preferences.
- *  @param tokenStore   The persistent store used to cache InstanceID tokens.
- *
- *  @return Store to cache tokens and checkin preferences.
- */
-- (instancetype)initWithCheckinStore:(FIRInstanceIDCheckinStore *)checkinStore
-                          tokenStore:(FIRInstanceIDTokenStore *)tokenStore;
-
-@end

+ 0 - 50
Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.m

@@ -1,50 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-
-@interface FIRInstanceIDTokenManager ()
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDStore *instanceIDStore;
-@property(nonatomic, readwrite, strong) FIRInstanceIDAuthService *authService;
-
-- (void)configureTokenOperations;
-
-@end
-
-@implementation FIRInstanceIDTokenManager (Test)
-
-- (instancetype)initWithCheckinStore:(FIRInstanceIDCheckinStore *)checkinStore
-                          tokenStore:(FIRInstanceIDTokenStore *)tokenStore {
-  self = [super init];
-  if (self) {
-    self.instanceIDStore = [[FIRInstanceIDStore alloc] initWithCheckinStore:checkinStore
-                                                                 tokenStore:tokenStore
-                                                                   delegate:self];
-    self.authService = [[FIRInstanceIDAuthService alloc] initWithStore:self.instanceIDStore];
-    [self configureTokenOperations];
-  }
-  return self;
-}
-
-- (void)store:(FIRInstanceIDStore *)store
-    didDeleteFCMScopedTokensForCheckin:(FIRInstanceIDCheckinPreferences *)checkin {
-}
-
-@end

+ 0 - 575
Example/InstanceID/Tests/FIRInstanceIDTokenManagerTest.m

@@ -1,575 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-
-#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
-
-#import "Example/InstanceID/Tests/FIRInstanceIDFakeKeychain.h"
-#import "Example/InstanceID/Tests/FIRInstanceIDTokenManager+Test.h"
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenStore.h"
-
-static NSString *const kSubDirectoryName = @"FirebaseInstanceIDTokenManagerTest";
-
-static NSString *const kAuthorizedEntity = @"test-authorized-entity";
-static NSString *const kScope = @"test-scope";
-static NSString *const kToken =
-    @"cHu_lDPF4EXfo3cdVQhfGg:APA91bGHesgrEsM5j8afb8kKKVwr2Q82NrX_mhLT0URVLYP_"
-    @"MVJgvrdNfYfgoiPO4NG8SYA2SsZofP0iRXUv9vKREhLPQh0JDOiQ1MO0ivJyDeRo6_5e8VXLeGTTa0StpzfqETEhMaW7";
-
-// Use a string (which is converted to NSData) as a placeholder for an actual APNs device token.
-static NSString *const kNewAPNSTokenString = @"newAPNSData";
-
-@interface FIRInstanceIDTokenOperation ()
-
-- (void)performTokenOperation;
-- (void)finishWithResult:(FIRInstanceIDTokenOperationResult)result
-                   token:(nullable NSString *)token
-                   error:(nullable NSError *)error;
-
-@end
-
-// A Fake operation that we have control over the returned error.
-// We are not using mocks here because we have no way of forcing NSOperationQueues to release
-// their operations, and this means that there is always going to be a race condition between
-// when we "stop" our partial mock vs when NSOperationQueue attempts to access the mock object on a
-// separate thread. We had mocks previously.
-@interface FIRInstanceIDTokenDeleteOperationFake : FIRInstanceIDTokenDeleteOperation
-@property(nonatomic, copy) NSError *error;
-@end
-
-@implementation FIRInstanceIDTokenDeleteOperationFake
-
-- (void)performTokenOperation {
-  if (self.error) {
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:self.error];
-  } else {
-    [self finishWithResult:FIRInstanceIDTokenOperationSucceeded token:kToken error:self.error];
-  }
-}
-
-@end
-
-@interface FIRInstanceIDTokenFetchOperationFake : FIRInstanceIDTokenFetchOperation
-@property(nonatomic, copy) NSError *error;
-@end
-
-@implementation FIRInstanceIDTokenFetchOperationFake
-
-- (void)performTokenOperation {
-  if (self.error) {
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:self.error];
-  } else {
-    [self finishWithResult:FIRInstanceIDTokenOperationSucceeded token:kToken error:self.error];
-  }
-}
-
-@end
-
-@interface FIRInstanceIDTokenManager (ExposedForTests)
-
-- (BOOL)checkTokenRefreshPolicyForIID:(NSString *)IID;
-- (void)updateToAPNSDeviceToken:(NSData *)deviceToken isSandbox:(BOOL)isSandbox;
-/**
- *  Create a fetch operation. This method can be stubbed to return a particular operation instance,
- *  which makes it easier to unit test different behaviors.
- */
-- (FIRInstanceIDTokenFetchOperation *)
-    createFetchOperationWithAuthorizedEntity:(NSString *)authorizedEntity
-                                       scope:(NSString *)scope
-                                     options:(NSDictionary<NSString *, NSString *> *)options
-                                  instanceID:(NSString *)instanceID;
-
-/**
- *  Create a delete operation. This method can be stubbed to return a particular operation instance,
- *  which makes it easier to unit test different behaviors.
- */
-- (FIRInstanceIDTokenDeleteOperation *)
-    createDeleteOperationWithAuthorizedEntity:(NSString *)authorizedEntity
-                                        scope:(NSString *)scope
-                           checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
-                                   instanceID:(NSString *)instanceID
-                                       action:(FIRInstanceIDTokenAction)action;
-@end
-
-@interface FIRInstanceIDTokenManagerTest : XCTestCase
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
-@property(nonatomic, readwrite, strong) id mockTokenManager;
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDBackupExcludedPlist *checkinPlist;
-@property(nonatomic, readwrite, strong) FIRInstanceIDFakeKeychain *fakeKeyChain;
-@property(nonatomic, readwrite, strong) FIRInstanceIDTokenStore *tokenStore;
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinPreferences *fakeCheckin;
-
-@property(nonatomic, readwrite, strong) id mockInstallations;
-@property(nonatomic, readwrite, strong) FIRInstallationsAuthTokenResult *FISAuthTokenResult;
-
-@end
-
-@implementation FIRInstanceIDTokenManagerTest
-
-- (void)setUp {
-  [super setUp];
-  [FIRInstanceIDStore createSubDirectory:kSubDirectoryName];
-
-  NSString *checkinPlistFilename = @"com.google.test.IIDCheckinTest";
-  self.checkinPlist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:checkinPlistFilename
-                                                    subDirectory:kSubDirectoryName];
-
-  // checkin store
-  FIRInstanceIDFakeKeychain *fakeCheckinKeychain = [[FIRInstanceIDFakeKeychain alloc] init];
-  FIRInstanceIDCheckinStore *checkinStore =
-      [[FIRInstanceIDCheckinStore alloc] initWithCheckinPlist:self.checkinPlist
-                                                     keychain:fakeCheckinKeychain];
-
-  // token store
-  self.fakeKeyChain = [[FIRInstanceIDFakeKeychain alloc] init];
-  self.tokenStore = [[FIRInstanceIDTokenStore alloc] initWithKeychain:_fakeKeyChain];
-
-  self.tokenManager = [[FIRInstanceIDTokenManager alloc] initWithCheckinStore:checkinStore
-                                                                   tokenStore:self.tokenStore];
-  self.mockTokenManager = OCMPartialMock(self.tokenManager);
-
-  self.fakeCheckin = [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:@"fakeDeviceID"
-                                                                   secretToken:@"fakeSecretToken"];
-
-  // Installations
-  self.FISAuthTokenResult = OCMClassMock([FIRInstallationsAuthTokenResult class]);
-  OCMStub([self.FISAuthTokenResult authToken]).andReturn(@"FISAuthToken");
-  OCMStub([self.FISAuthTokenResult expirationDate]).andReturn([NSDate distantFuture]);
-
-  self.mockInstallations = OCMClassMock([FIRInstallations class]);
-  OCMStub([self.mockInstallations installations]).andReturn(self.mockInstallations);
-  id authTokenBlockArg = [OCMArg invokeBlockWithArgs:self.FISAuthTokenResult, [NSNull null], nil];
-  OCMStub([self.mockInstallations authTokenWithCompletion:authTokenBlockArg]);
-}
-
-- (void)tearDown {
-  self.fakeCheckin = nil;
-
-  [self.mockTokenManager stopMocking];
-  self.mockTokenManager = nil;
-
-  self.tokenManager = nil;
-  self.tokenStore = nil;
-  self.fakeKeyChain = nil;
-
-  NSError *error;
-  if (![self.checkinPlist deleteFile:&error]) {
-    XCTFail(@"Failed to delete checkin plist %@", error);
-  }
-  self.checkinPlist = nil;
-
-  [FIRInstanceIDStore removeSubDirectory:kSubDirectoryName error:nil];
-  [super tearDown];
-}
-
-/**
- *  Tests that when a new InstanceID token is successfully produced,
- *  the callback is invoked with a token that is not an empty string and with no error.
- */
-- (void)testNewTokenSuccess {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = [NSDictionary dictionary];
-
-  // Create a fake operation that always returns success
-  FIRInstanceIDTokenFetchOperationFake *operation =
-      [[FIRInstanceIDTokenFetchOperationFake alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                       scope:kScope
-                                                                     options:tokenOptions
-                                                          checkinPreferences:self.fakeCheckin
-                                                                  instanceID:[OCMArg any]];
-  XCTestExpectation *operationFinishExpectation =
-      [self expectationWithDescription:@"operationFinishExpectation"];
-  operation.completionBlock = ^{
-    [operationFinishExpectation fulfill];
-  };
-
-  // Return our fake operation when asked for an operation
-  [[[self.mockTokenManager stub] andReturn:operation]
-      createFetchOperationWithAuthorizedEntity:[OCMArg any]
-                                         scope:[OCMArg any]
-                                       options:[OCMArg any]
-                                    instanceID:[OCMArg any]];
-
-  [self.tokenManager fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                                 scope:kScope
-                                            instanceID:[OCMArg any]
-                                               options:tokenOptions
-                                               handler:^(NSString *token, NSError *error) {
-                                                 XCTAssertNotNil(token);
-                                                 XCTAssertGreaterThan(token.length, 0);
-                                                 XCTAssertNil(error);
-                                                 [tokenExpectation fulfill];
-                                               }];
-
-  [self waitForExpectations:@[ tokenExpectation, operationFinishExpectation ] timeout:1];
-}
-
-/**
- *  Tests that when a new InstanceID token is fetched from the server but unsuccessfully
- *  saved on the client we should return an error instead of the fetched token.
- */
-- (void)testNewTokenSaveFailure {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = [NSDictionary dictionary];
-  // Simulate write to keychain failure.
-  self.fakeKeyChain.cannotWriteToKeychain = YES;
-
-  // Create a fake operation that always returns success
-  FIRInstanceIDTokenFetchOperationFake *operation =
-      [[FIRInstanceIDTokenFetchOperationFake alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                       scope:kScope
-                                                                     options:tokenOptions
-                                                          checkinPreferences:self.fakeCheckin
-                                                                  instanceID:[OCMArg any]];
-
-  XCTestExpectation *operationFinishExpectation =
-      [self expectationWithDescription:@"operationFinishExpectation"];
-  operation.completionBlock = ^{
-    [operationFinishExpectation fulfill];
-  };
-
-  // Return our fake operation when asked for an operation
-  [[[self.mockTokenManager stub] andReturn:operation]
-      createFetchOperationWithAuthorizedEntity:[OCMArg any]
-                                         scope:[OCMArg any]
-                                       options:[OCMArg any]
-                                    instanceID:[OCMArg any]];
-
-  [self.tokenManager fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                                 scope:kScope
-                                            instanceID:[OCMArg any]
-                                               options:tokenOptions
-                                               handler:^(NSString *token, NSError *error) {
-                                                 XCTAssertNil(token);
-                                                 XCTAssertNotNil(error);
-                                                 [tokenExpectation fulfill];
-                                               }];
-
-  [self waitForExpectations:@[ tokenExpectation, operationFinishExpectation ] timeout:1];
-}
-
-/**
- *  Tests that when there is a failure in producing a new InstanceID token,
- *  the callback is invoked with an error and a nil token.
- */
-- (void)testNewTokenFailure {
-  XCTestExpectation *tokenExpectation =
-      [self expectationWithDescription:@"New token handler invoked."];
-
-  NSDictionary *tokenOptions = [NSDictionary dictionary];
-
-  // Create a fake operation that always returns failure
-  FIRInstanceIDTokenFetchOperationFake *operation =
-      [[FIRInstanceIDTokenFetchOperationFake alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                       scope:kScope
-                                                                     options:tokenOptions
-                                                          checkinPreferences:self.fakeCheckin
-                                                                  instanceID:[OCMArg any]];
-  operation.error = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
-
-  XCTestExpectation *operationFinishExpectation =
-      [self expectationWithDescription:@"operationFinishExpectation"];
-  operation.completionBlock = ^{
-    [operationFinishExpectation fulfill];
-  };
-  // Return our fake operation when asked for an operation
-  [[[self.mockTokenManager stub] andReturn:operation]
-      createFetchOperationWithAuthorizedEntity:[OCMArg any]
-                                         scope:[OCMArg any]
-                                       options:[OCMArg any]
-                                    instanceID:[OCMArg any]];
-
-  [self.tokenManager fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
-                                                 scope:kScope
-                                            instanceID:[OCMArg any]
-                                               options:tokenOptions
-                                               handler:^(NSString *token, NSError *error) {
-                                                 XCTAssertNil(token);
-                                                 XCTAssertNotNil(error);
-                                                 [tokenExpectation fulfill];
-                                               }];
-
-  [self waitForExpectations:@[ tokenExpectation, operationFinishExpectation ] timeout:1];
-}
-
-/**
- *  Tests that when a token is deleted successfully, the callback is invoked with no error.
- */
-- (void)testDeleteTokenSuccess {
-  XCTestExpectation *deleteExpectation =
-      [self expectationWithDescription:@"Delete handler invoked."];
-
-  // Create a fake operation that always succeeds
-  FIRInstanceIDTokenDeleteOperationFake *operation = [[FIRInstanceIDTokenDeleteOperationFake alloc]
-      initWithAuthorizedEntity:kAuthorizedEntity
-                         scope:kScope
-            checkinPreferences:self.fakeCheckin
-                    instanceID:[OCMArg any]
-                        action:FIRInstanceIDTokenActionDeleteToken];
-
-  XCTestExpectation *operationFinishExpectation =
-      [self expectationWithDescription:@"operationFinishExpectation"];
-  operation.completionBlock = ^{
-    [operationFinishExpectation fulfill];
-  };
-
-  // Return our fake operation when asked for an operation
-  [[[self.mockTokenManager stub] andReturn:operation]
-      createDeleteOperationWithAuthorizedEntity:[OCMArg any]
-                                          scope:[OCMArg any]
-                             checkinPreferences:[OCMArg any]
-                                     instanceID:[OCMArg any]
-                                         action:FIRInstanceIDTokenActionDeleteToken];
-
-  [self.tokenManager deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                                               scope:kScope
-                                          instanceID:[OCMArg any]
-                                             handler:^(NSError *error) {
-                                               XCTAssertNil(error);
-                                               [deleteExpectation fulfill];
-                                             }];
-
-  [self waitForExpectations:@[ deleteExpectation, operationFinishExpectation ] timeout:1];
-}
-
-/**
- *  Tests that when a token deletion fails, the callback is invoked with an error.
- */
-- (void)testDeleteTokenFailure {
-  XCTestExpectation *deleteExpectation =
-      [self expectationWithDescription:@"Delete handler invoked."];
-
-  // Create a fake operation that always fails
-  FIRInstanceIDTokenDeleteOperationFake *operation = [[FIRInstanceIDTokenDeleteOperationFake alloc]
-      initWithAuthorizedEntity:kAuthorizedEntity
-                         scope:kScope
-            checkinPreferences:self.fakeCheckin
-                    instanceID:[OCMArg any]
-                        action:FIRInstanceIDTokenActionDeleteToken];
-  operation.error = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
-
-  XCTestExpectation *operationFinishExpectation =
-      [self expectationWithDescription:@"operationFinishExpectation"];
-  operation.completionBlock = ^{
-    [operationFinishExpectation fulfill];
-  };
-
-  // Return our fake operation when asked for an operation
-  [[[self.mockTokenManager stub] andReturn:operation]
-      createDeleteOperationWithAuthorizedEntity:[OCMArg any]
-                                          scope:[OCMArg any]
-                             checkinPreferences:[OCMArg any]
-                                     instanceID:[OCMArg any]
-                                         action:FIRInstanceIDTokenActionDeleteToken];
-
-  [self.tokenManager deleteTokenWithAuthorizedEntity:kAuthorizedEntity
-                                               scope:kScope
-                                          instanceID:[OCMArg any]
-                                             handler:^(NSError *error) {
-                                               XCTAssertNotNil(error);
-                                               [deleteExpectation fulfill];
-                                             }];
-
-  [self waitForExpectations:@[ deleteExpectation, operationFinishExpectation ] timeout:1];
-}
-
-#pragma mark - Cached Token Invalidation
-
-- (void)testCachedTokensInvalidatedOnAppVersionChange {
-  // Write some fake tokens to cache with a old app version "0.9"
-  NSArray<NSString *> *entities = @[ @"entity1", @"entity2" ];
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *info =
-        [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:entity
-                                                           scope:kScope
-                                                           token:@"abcdef"
-                                                      appVersion:@"0.9"
-                                                   firebaseAppID:nil];
-    [self.tokenStore saveTokenInfo:info handler:nil];
-  }
-
-  // Ensure they tokens now exist.
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-
-  // Trigger a potential reset, the current app version is 1.0 which is newer than
-  // the one set in tokenInfo.
-  [self.tokenManager checkTokenRefreshPolicyWithIID:@"abc"];
-
-  // Ensure that token data is now missing
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNil(cachedTokenInfo);
-  }
-}
-
-- (void)testTokenShouldBeDeletedIfWrongFormat {
-  // Cache some token
-  NSArray<NSString *> *entities = @[ @"entity1", @"entity2" ];
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *info = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:entity
-                                                                                      scope:kScope
-                                                                                      token:kToken
-                                                                                 appVersion:nil
-                                                                              firebaseAppID:nil];
-    [self.tokenStore saveTokenInfo:info handler:nil];
-  }
-
-  // Ensure they tokens now exist.
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-
-  // Trigger a potential reset, the current IID is sth differnt than the token
-  [self.tokenManager checkTokenRefreshPolicyWithIID:@"d8xQyABOoV8"];
-
-  // Ensure that token data is now missing
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNil(cachedTokenInfo);
-  }
-}
-
-- (void)testCachedTokensInvalidatedOnAPNSAddition {
-  // Write some fake tokens to cache, which have no APNs info
-  NSArray<NSString *> *entities = @[ @"entity1", @"entity2" ];
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *info = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:entity
-                                                                                      scope:kScope
-                                                                                      token:kToken
-                                                                                 appVersion:nil
-                                                                              firebaseAppID:nil];
-    [self.tokenStore saveTokenInfo:info handler:nil];
-  }
-
-  // Ensure the tokens now exist.
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-
-  // Trigger a potential reset.
-  [self triggerAPNSTokenChange];
-
-  // Ensure that token data is now missing
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNil(cachedTokenInfo);
-  }
-}
-
-- (void)testCachedTokensInvalidatedOnAPNSChange {
-  // Write some fake tokens to cache
-  NSArray<NSString *> *entities = @[ @"entity1", @"entity2" ];
-  NSData *oldAPNSData = [@"oldAPNSToken" dataUsingEncoding:NSUTF8StringEncoding];
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *info = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:entity
-                                                                                      scope:kScope
-                                                                                      token:kToken
-                                                                                 appVersion:nil
-                                                                              firebaseAppID:nil];
-    info.APNSInfo = [[FIRInstanceIDAPNSInfo alloc] initWithDeviceToken:oldAPNSData isSandbox:NO];
-    [self.tokenStore saveTokenInfo:info handler:nil];
-  }
-
-  // Ensure the tokens now exist.
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-
-  // Trigger a potential reset.
-  [self triggerAPNSTokenChange];
-
-  // Ensure that token data is now missing
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNil(cachedTokenInfo);
-  }
-}
-
-- (void)testCachedTokensNotInvalidatedIfAPNSSame {
-  // Write some fake tokens to cache, with the current APNs token
-  NSArray<NSString *> *entities = @[ @"entity1", @"entity2" ];
-  NSString *apnsDataString = kNewAPNSTokenString;
-  NSData *currentAPNSData = [apnsDataString dataUsingEncoding:NSUTF8StringEncoding];
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *info = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:entity
-                                                                                      scope:kScope
-                                                                                      token:kToken
-                                                                                 appVersion:nil
-                                                                              firebaseAppID:nil];
-    info.APNSInfo = [[FIRInstanceIDAPNSInfo alloc] initWithDeviceToken:currentAPNSData
-                                                             isSandbox:NO];
-    [self.tokenStore saveTokenInfo:info handler:nil];
-  }
-
-  // Ensure the tokens now exist.
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-
-  // Trigger a potential reset.
-  [self triggerAPNSTokenChange];
-
-  // Ensure that token data is still there
-  for (NSString *entity in entities) {
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:entity scope:kScope];
-    XCTAssertNotNil(cachedTokenInfo);
-  }
-}
-
-- (void)triggerAPNSTokenChange {
-  // Trigger a potential reset.
-  NSData *deviceToken = [kNewAPNSTokenString dataUsingEncoding:NSUTF8StringEncoding];
-  [self.tokenManager updateTokensToAPNSDeviceToken:deviceToken isSandbox:NO];
-}
-
-@end

+ 0 - 420
Example/InstanceID/Tests/FIRInstanceIDTokenOperationsTest.m

@@ -1,420 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import "Firebase/InstanceID/Public/FIRInstanceID.h"
-
-#import <OCMock/OCMock.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDKeychain.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation+Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-
-#import <GoogleUtilities/GULHeartbeatDateStorage.h>
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
-
-static NSString *kDeviceID = @"fakeDeviceID";
-static NSString *kSecretToken = @"fakeSecretToken";
-static NSString *kDigestString = @"test-digest";
-static NSString *kVersionInfoString = @"version_info-1.0.0";
-static NSString *kAuthorizedEntity = @"sender-1234567";
-static NSString *kScope = @"fcm";
-static NSString *kRegistrationToken = @"token-12345";
-
-@interface FIRInstanceIDTokenOperation (ExposedForTest)
-- (void)performTokenOperation;
-@end
-
-@interface FIRInstallationsAuthTokenResult (Tests)
-- (instancetype)initWithToken:(NSString *)token expirationDate:(NSDate *)expirationDate;
-@end
-
-// A Fake operation that allows us to check that perform was called.
-// We are not using mocks here because we have no way of forcing NSOperationQueues to release
-// their operations, and this means that there is always going to be a race condition between
-// when we "stop" our partial mock vs when NSOperationQueue attempts to access the mock object on a
-// separate thread. We had mocks previously.
-@interface FIRInstanceIDTokenOperationFake : FIRInstanceIDTokenOperation
-@property(nonatomic, assign) BOOL performWasCalled;
-@end
-
-@implementation FIRInstanceIDTokenOperationFake
-
-- (void)performTokenOperation {
-  self.performWasCalled = YES;
-}
-
-@end
-
-@interface FIRInstanceIDTokenOperationsTest : XCTestCase
-
-@property(strong, readonly, nonatomic) FIRInstanceIDAuthService *authService;
-@property(strong, readonly, nonatomic) id mockAuthService;
-
-@property(strong, readonly, nonatomic) id mockStore;
-@property(strong, readonly, nonatomic) FIRInstanceIDCheckinService *checkinService;
-@property(strong, readonly, nonatomic) id mockCheckinService;
-@property(strong, readonly, nonatomic) id mockInstallations;
-
-@property(strong, readonly, nonatomic) NSString *instanceID;
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinPreferences *checkinPreferences;
-
-@end
-
-@implementation FIRInstanceIDTokenOperationsTest
-
-- (void)setUp {
-  [super setUp];
-  _mockStore = OCMClassMock([FIRInstanceIDStore class]);
-  _checkinService = [[FIRInstanceIDCheckinService alloc] init];
-  _mockCheckinService = OCMPartialMock(_checkinService);
-  _authService = [[FIRInstanceIDAuthService alloc] initWithCheckinService:_mockCheckinService
-                                                                    store:_mockStore];
-  _instanceID = @"instanceID";
-
-  // `FIRInstanceIDTokenOperation` uses `FIRInstallations` under the hood to get FIS auth token.
-  // Stub `FIRInstallations` to avoid using a real object.
-  [self stubInstallations];
-
-  NSString *const kHeartbeatStorageFile = @"HEARTBEAT_INFO_STORAGE";
-  GULHeartbeatDateStorage *dataStorage =
-      [[GULHeartbeatDateStorage alloc] initWithFileName:kHeartbeatStorageFile];
-  [[NSFileManager defaultManager] removeItemAtURL:[dataStorage fileURL] error:nil];
-}
-
-- (void)tearDown {
-  [_mockInstallations stopMocking];
-  _mockInstallations = nil;
-  _authService = nil;
-  [_mockCheckinService stopMocking];
-  _mockCheckinService = nil;
-  _checkinService = nil;
-  _mockStore = nil;
-}
-
-- (void)testThatTokenOperationsAuthHeaderStringMatchesCheckin {
-  int64_t tenHoursAgo = FIRInstanceIDCurrentTimestampInMilliseconds() - 10 * 60 * 60 * 1000;
-  FIRInstanceIDCheckinPreferences *checkin =
-      [self setCheckinPreferencesWithLastCheckinTime:tenHoursAgo];
-
-  NSString *expectedAuthHeader = [FIRInstanceIDTokenOperation HTTPAuthHeaderFromCheckin:checkin];
-  XCTestExpectation *authHeaderMatchesCheckinExpectation =
-      [self expectationWithDescription:@"Auth header string in request matches checkin info"];
-  FIRInstanceIDTokenFetchOperation *operation =
-      [[FIRInstanceIDTokenFetchOperation alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                   scope:kScope
-                                                                 options:nil
-                                                      checkinPreferences:checkin
-                                                              instanceID:self.instanceID];
-  operation.testBlock =
-      ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock response) {
-        NSDictionary<NSString *, NSString *> *headers = request.allHTTPHeaderFields;
-        NSString *authHeader = headers[@"Authorization"];
-        if ([authHeader isEqualToString:expectedAuthHeader]) {
-          [authHeaderMatchesCheckinExpectation fulfill];
-        }
-
-        // Return a response (doesnt matter what the response is)
-        NSData *responseBody = [self dataForFetchRequest:request returnValidToken:YES];
-        NSHTTPURLResponse *responseObject = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                                        statusCode:200
-                                                                       HTTPVersion:@"HTTP/1.1"
-                                                                      headerFields:nil];
-        response(responseBody, responseObject, nil);
-      };
-
-  [operation start];
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-- (void)testThatTokenOperationWithoutCheckInFails {
-  // If asserts are enabled, test for the assert to be thrown, otherwise check for the resulting
-  // error in the completion handler.
-  XCTestExpectation *failedExpectation =
-      [self expectationWithDescription:@"Operation failed without checkin info"];
-
-  // This will return hasCheckinInfo == NO
-  FIRInstanceIDCheckinPreferences *emptyCheckinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:@"" secretToken:@""];
-
-  FIRInstanceIDTokenOperation *operation =
-      [[FIRInstanceIDTokenOperation alloc] initWithAction:FIRInstanceIDTokenActionFetch
-                                      forAuthorizedEntity:kAuthorizedEntity
-                                                    scope:kScope
-                                                  options:nil
-                                       checkinPreferences:emptyCheckinPreferences
-                                               instanceID:self.instanceID];
-  [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
-                                    NSString *_Nullable token, NSError *_Nullable error) {
-    [failedExpectation fulfill];
-  }];
-
-  @try {
-    [operation start];
-  } @catch (NSException *exception) {
-    if (exception.name == NSInternalInconsistencyException) {
-      [failedExpectation fulfill];
-    }
-  } @finally {
-  }
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-- (void)testThatAnAlreadyCancelledOperationFinishesWithoutStarting {
-  XCTestExpectation *cancelledExpectation =
-      [self expectationWithDescription:@"Operation finished as cancelled"];
-  XCTestExpectation *didNotCallPerform =
-      [self expectationWithDescription:@"Did not call performTokenOperation"];
-
-  int64_t tenHoursAgo = FIRInstanceIDCurrentTimestampInMilliseconds() - 10 * 60 * 60 * 1000;
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [self setCheckinPreferencesWithLastCheckinTime:tenHoursAgo];
-
-  FIRInstanceIDTokenOperationFake *operation =
-      [[FIRInstanceIDTokenOperationFake alloc] initWithAction:FIRInstanceIDTokenActionFetch
-                                          forAuthorizedEntity:kAuthorizedEntity
-                                                        scope:kScope
-                                                      options:nil
-                                           checkinPreferences:checkinPreferences
-                                                   instanceID:self.instanceID];
-  operation.performWasCalled = NO;
-  __weak FIRInstanceIDTokenOperationFake *weakOperation = operation;
-  [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
-                                    NSString *_Nullable token, NSError *_Nullable error) {
-    if (result == FIRInstanceIDTokenOperationCancelled) {
-      [cancelledExpectation fulfill];
-    }
-
-    if (!weakOperation.performWasCalled) {
-      [didNotCallPerform fulfill];
-    }
-  }];
-
-  [operation cancel];
-  [operation start];
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-- (void)testThatOptionsDictionaryIsIncludedWithFetchRequest {
-  XCTestExpectation *optionsIncludedExpectation =
-      [self expectationWithDescription:@"Options keys were included in token URL request"];
-  int64_t tenHoursAgo = FIRInstanceIDCurrentTimestampInMilliseconds() - 10 * 60 * 60 * 1000;
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [self setCheckinPreferencesWithLastCheckinTime:tenHoursAgo];
-  NSData *fakeDeviceToken = [@"fakeAPNSToken" dataUsingEncoding:NSUTF8StringEncoding];
-  BOOL isSandbox = NO;
-  NSString *apnsTupleString =
-      FIRInstanceIDAPNSTupleStringForTokenAndServerType(fakeDeviceToken, isSandbox);
-  NSDictionary *options = @{
-    kFIRInstanceIDTokenOptionsFirebaseAppIDKey : @"fakeGMPAppID",
-    kFIRInstanceIDTokenOptionsAPNSKey : fakeDeviceToken,
-    kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandbox),
-  };
-
-  FIRInstanceIDTokenFetchOperation *operation =
-      [[FIRInstanceIDTokenFetchOperation alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                   scope:kScope
-                                                                 options:options
-                                                      checkinPreferences:checkinPreferences
-                                                              instanceID:self.instanceID];
-  operation.testBlock =
-      ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock response) {
-        NSString *query = [[NSString alloc] initWithData:request.HTTPBody
-                                                encoding:NSUTF8StringEncoding];
-        NSString *gmpAppIDQueryTuple =
-            [NSString stringWithFormat:@"%@=%@", kFIRInstanceIDTokenOptionsFirebaseAppIDKey,
-                                       options[kFIRInstanceIDTokenOptionsFirebaseAppIDKey]];
-        NSRange gmpAppIDRange = [query rangeOfString:gmpAppIDQueryTuple];
-
-        NSString *apnsQueryTuple = [NSString
-            stringWithFormat:@"%@=%@", kFIRInstanceIDTokenOptionsAPNSKey, apnsTupleString];
-        NSRange apnsRange = [query rangeOfString:apnsQueryTuple];
-
-        if (gmpAppIDRange.location != NSNotFound && apnsRange.location != NSNotFound) {
-          [optionsIncludedExpectation fulfill];
-        }
-
-        // Return a response (doesnt matter what the response is)
-        NSData *responseBody = [self dataForFetchRequest:request returnValidToken:YES];
-        NSHTTPURLResponse *responseObject = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                                        statusCode:200
-                                                                       HTTPVersion:@"HTTP/1.1"
-                                                                      headerFields:nil];
-        response(responseBody, responseObject, nil);
-      };
-
-  [operation start];
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-- (void)testServerResetCommand {
-  XCTestExpectation *shouldResetIdentityExpectation =
-      [self expectationWithDescription:
-                @"When server sends down RST error, clients should return reset identity error."];
-  int64_t tenHoursAgo = FIRInstanceIDCurrentTimestampInMilliseconds() - 10 * 60 * 60 * 1000;
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [self setCheckinPreferencesWithLastCheckinTime:tenHoursAgo];
-
-  FIRInstanceIDTokenFetchOperation *operation =
-      [[FIRInstanceIDTokenFetchOperation alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                   scope:kScope
-                                                                 options:nil
-                                                      checkinPreferences:checkinPreferences
-                                                              instanceID:self.instanceID];
-  operation.testBlock =
-      ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock response) {
-        // Return a response with Error=RST
-        NSData *responseBody = [self dataForFetchRequest:request returnValidToken:NO];
-        NSHTTPURLResponse *responseObject = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                                        statusCode:200
-                                                                       HTTPVersion:@"HTTP/1.1"
-                                                                      headerFields:nil];
-        response(responseBody, responseObject, nil);
-      };
-
-  [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
-                                    NSString *_Nullable token, NSError *_Nullable error) {
-    XCTAssertEqual(result, FIRInstanceIDTokenOperationError);
-    XCTAssertNotNil(error);
-    XCTAssertEqual(error.code, kFIRInstanceIDErrorCodeInvalidIdentity);
-
-    [shouldResetIdentityExpectation fulfill];
-  }];
-
-  [operation start];
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-- (void)testHTTPAuthHeaderGenerationFromCheckin {
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceID secretToken:kSecretToken];
-  NSString *expectedHeader =
-      [NSString stringWithFormat:@"AidLogin %@:%@", checkinPreferences.deviceID,
-                                 checkinPreferences.secretToken];
-  NSString *generatedHeader =
-      [FIRInstanceIDTokenOperation HTTPAuthHeaderFromCheckin:checkinPreferences];
-  XCTAssertEqualObjects(generatedHeader, expectedHeader);
-}
-
-- (void)testTokenFetchOperationFirebaseUserAgentAndHeartbeatHeader {
-  XCTestExpectation *completionExpectation =
-      [self expectationWithDescription:@"completionExpectation"];
-
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [self setCheckinPreferencesWithLastCheckinTime:0];
-
-  FIRInstanceIDTokenFetchOperation *operation =
-      [[FIRInstanceIDTokenFetchOperation alloc] initWithAuthorizedEntity:kAuthorizedEntity
-                                                                   scope:kScope
-                                                                 options:nil
-                                                      checkinPreferences:checkinPreferences
-                                                              instanceID:self.instanceID];
-  operation.testBlock =
-      ^(NSURLRequest *request, FIRInstanceIDURLRequestTestResponseBlock response) {
-        NSString *userAgentValue = request.allHTTPHeaderFields[kFIRInstanceIDFirebaseUserAgentKey];
-        XCTAssertEqualObjects(userAgentValue, [FIRApp firebaseUserAgent]);
-        NSString *heartBeatCode = request.allHTTPHeaderFields[kFIRInstanceIDFirebaseHeartbeatKey];
-        XCTAssertEqualObjects(heartBeatCode, @"3");
-
-        // Return a response with Error=RST
-        NSData *responseBody = [self dataForFetchRequest:request returnValidToken:NO];
-        NSHTTPURLResponse *responseObject = [[NSHTTPURLResponse alloc] initWithURL:request.URL
-                                                                        statusCode:200
-                                                                       HTTPVersion:@"HTTP/1.1"
-                                                                      headerFields:nil];
-        response(responseBody, responseObject, nil);
-      };
-
-  [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
-                                    NSString *_Nullable token, NSError *_Nullable error) {
-    [completionExpectation fulfill];
-  }];
-
-  [operation start];
-
-  [self waitForExpectationsWithTimeout:0.25
-                               handler:^(NSError *_Nullable error) {
-                                 XCTAssertNil(error.localizedDescription);
-                               }];
-}
-
-#pragma mark - Internal Helpers
-- (NSData *)dataForFetchRequest:(NSURLRequest *)request returnValidToken:(BOOL)returnValidToken {
-  NSString *response;
-  if (returnValidToken) {
-    response = [NSString stringWithFormat:@"token=%@", kRegistrationToken];
-  } else {
-    response = @"Error=RST";
-  }
-  return [response dataUsingEncoding:NSUTF8StringEncoding];
-}
-
-- (FIRInstanceIDCheckinPreferences *)setCheckinPreferencesWithLastCheckinTime:(int64_t)time {
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceID secretToken:kSecretToken];
-  NSDictionary *checkinPlistContents = @{
-    kFIRInstanceIDDigestStringKey : kDigestString,
-    kFIRInstanceIDVersionInfoStringKey : kVersionInfoString,
-    kFIRInstanceIDLastCheckinTimeKey : @(time)
-  };
-  [checkinPreferences updateWithCheckinPlistContents:checkinPlistContents];
-  // manually initialize the checkin preferences
-  self.checkinPreferences = checkinPreferences;
-  return checkinPreferences;
-}
-
-- (void)stubInstallations {
-  _mockInstallations = OCMClassMock([FIRInstallations class]);
-  OCMStub([_mockInstallations installations]).andReturn(_mockInstallations);
-  FIRInstallationsAuthTokenResult *authToken =
-      [[FIRInstallationsAuthTokenResult alloc] initWithToken:@"fis-auth-token"
-                                              expirationDate:[NSDate distantFuture]];
-  id authTokenWithCompletionArg = [OCMArg invokeBlockWithArgs:authToken, [NSNull null], nil];
-  OCMStub([_mockInstallations authTokenWithCompletion:authTokenWithCompletionArg]);
-}
-
-@end

+ 0 - 95
Example/InstanceID/Tests/FIRInstanceIDUtilitiesTest.m

@@ -1,95 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <XCTest/XCTest.h>
-
-#import <OCMock/OCMock.h>
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-
-@interface FIRInstanceIDUtilitiesTest : XCTestCase
-
-@property(nonatomic, strong) id mainBundleMock;
-
-@end
-
-@implementation FIRInstanceIDUtilitiesTest
-
-- (void)setUp {
-  _mainBundleMock = OCMPartialMock([NSBundle mainBundle]);
-  [super setUp];
-}
-
-- (void)tearDown {
-  [_mainBundleMock stopMocking];
-  [super tearDown];
-}
-
-- (void)testAPNSTupleStringReturnsNilIfDeviceTokenNil {
-  NSString *tupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(nil, NO);
-  XCTAssertNil(tupleString);
-}
-
-- (void)testAPNSTupleStringReturnsValidData {
-  NSData *deviceToken = [@"FAKE_DEVICE_TOKEN" dataUsingEncoding:NSUTF8StringEncoding];
-  NSString *expectedTokenString = FIRInstanceIDStringForAPNSDeviceToken(deviceToken);
-  NSString *tupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(deviceToken, NO);
-  NSArray<NSString *> *components = [tupleString componentsSeparatedByString:@"_"];
-  XCTAssertTrue(components.count == 2);
-  XCTAssertEqualObjects(components.firstObject, @"p");
-  XCTAssertEqualObjects(components.lastObject, expectedTokenString);
-}
-
-- (void)testAppVersionReturnsExpectedValue {
-  NSString *expectedVersion = @"1.2.3";
-  NSDictionary *fakeInfoDictionary = @{@"CFBundleShortVersionString" : expectedVersion};
-  [[[_mainBundleMock stub] andReturn:fakeInfoDictionary] infoDictionary];
-  NSString *appVersion = FIRInstanceIDCurrentAppVersion();
-  XCTAssertEqualObjects(appVersion, expectedVersion);
-}
-
-- (void)testAppVersionReturnsEmptyStringWhenNotFound {
-  NSDictionary *fakeInfoDictionary = @{};
-  [[[_mainBundleMock stub] andReturn:fakeInfoDictionary] infoDictionary];
-  NSString *appVersion = FIRInstanceIDCurrentAppVersion();
-  XCTAssertEqualObjects(appVersion, @"");
-}
-
-- (void)testAppIdentifierReturnsExpectedValue {
-  NSString *expectedIdentifier = @"com.me.myapp";
-  [[[_mainBundleMock stub] andReturn:expectedIdentifier] bundleIdentifier];
-  NSString *appIdentifier = FIRInstanceIDAppIdentifier();
-  XCTAssertEqualObjects(appIdentifier, expectedIdentifier);
-}
-
-- (void)testAppIdentifierReturnsEmptyStringWhenNotFound {
-  [[[_mainBundleMock stub] andReturn:nil] bundleIdentifier];
-  NSString *appIdentifier = FIRInstanceIDAppIdentifier();
-  XCTAssertEqualObjects(appIdentifier, @"");
-}
-
-- (void)testLocaleHasChanged {
-  NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
-  [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
-  XCTAssertTrue(FIRInstanceIDHasLocaleChanged());
-  [[NSUserDefaults standardUserDefaults] setObject:FIRInstanceIDCurrentLocale()
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  XCTAssertFalse(FIRInstanceIDHasLocaleChanged());
-  [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hant"
-                                            forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  XCTAssertTrue(FIRInstanceIDHasLocaleChanged());
-}
-
-@end

+ 0 - 22
Example/InstanceID/Tests/Info.plist

@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-	<key>CFBundleDevelopmentRegion</key>
-	<string>en</string>
-	<key>CFBundleExecutable</key>
-	<string>$(EXECUTABLE_NAME)</string>
-	<key>CFBundleIdentifier</key>
-	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>$(PRODUCT_NAME)</string>
-	<key>CFBundlePackageType</key>
-	<string>BNDL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>1.0</string>
-	<key>CFBundleVersion</key>
-	<string>1</string>
-</dict>
-</plist>

+ 0 - 2
Example/watchOSSample/Podfile

@@ -9,7 +9,6 @@ target 'SampleWatchAppWatchKitExtension' do
 
   pod 'FirebaseCore', :path => '../../'
   pod 'FirebaseMessaging', :path => '../../'
-  pod 'FirebaseInstanceID', :path => '../../'
   pod 'FirebaseCoreDiagnostics', :path => '../../'
   pod 'FirebaseInstallations', :path => '../../'
   pod 'FirebaseStorage', :path => '../../'
@@ -28,5 +27,4 @@ end
 target 'ServiceExtension' do
   platform :watchos, '7.0'
   pod 'FirebaseMessaging', :path => '../../'
-  pod 'FirebaseInstanceID', :path => '../../'
 end

+ 0 - 237
Firebase/InstanceID/CHANGELOG.md

@@ -1,237 +0,0 @@
-# 2021-01 -- 7.4.0
-- [changed] Added a check on whether the default token has been changed by Messaging before writing to the InstanceID keychain storage. (#7223)
-
-# 2020-10 -- 7.0.0
-- [changed] Deprecated private `-[FIRInstanceID appInstanceID:]` method was removed. (#4486)
-- [fixed] Fixed an issue that APNS token is not sent in token request when there's a delay of getting the APNS token from Apple. (#6553)
-
-# 2020-09 -- 4.7.0
-- [deprecated] Deprecated InstanceID. For app instance identity handling, use FirebaseInstallations. For FCM registration token handling, use FirebaseMessaging. (#6585)
-
-# 2020-08 -- 4.6.0
-- [added] Added a new notification listening token refresh from Messaging and update the token cache in InstanceID. (#6286)
-- [fixed] Fixed an issue that token refresh notification is not triggered when use `tokenWithAuthorizedEntity:scope:options:handler` to get token. (#6286)
-
-# 2020-07 -- 4.5.1
-- [changed] Remove FIRInstanceIDURLQueryItem in favor of NSURLQueryItem. (#5835)
-
-# 2020-07 -- 4.5.0
-- [changed] Functionally neutral updated import references for dependencies. (#5824)
-
-# 2020-06 -- 4.4.0
-- [changed] Standardize FirebaseCore import headers. (#5758)
-
-# 2020-04 -- 4.3.4
-- [changed] Internal cleanup and remove repetitive local notification. (#5339)
-
-# 2020-03 -- 4.3.3
-- [fixed] Fixed provisioning profile location for catalyst. (#5048)
-- [fixed] Fixed crash when passing a nil handler to deleteToken request. (#5247)
-- [changed] Remove obsolete logic to improve performance and reduce keychain operations. (#5211, #5237)
-
-# 2020-02 -- 4.3.2
-- [changed] Removed unused files (#4881).
-
-# 2020-02 -- 4.3.1
-- [changed] Stop collecting logging ID as it is not used anymore.(#4444)
-
-# 2020-01 -- 4.3.0
-- [added] Added watchOS support for InstanceID (#4016)
-- [added] Added a new dependency on the [Firebase Installations SDK](../../FirebaseInstallations/CHANGELOG.md). The Firebase Installations SDK introduces the [Firebase Installations API](https://console.cloud.google.com/apis/library/firebaseinstallations.googleapis.com). Developers that use API-restrictions for their API-Keys may experience blocked requests (https://stackoverflow.com/questions/58495985/). A solution is available [here](../../FirebaseInstallations/API_KEY_RESTRICTIONS.md). (#4533)
-
-# 2019-12 -- 4.2.8
-- [changed] Added heartbeat support for InstanceID (#4323)
-- [fixed] Fixed the documentations on a few random generation and hash methods to clarify its use case to avoid confusions. (#4469, #4444, #4326)
-
-# 2019-11-05 -- 4.2.7
-- [fixed] Fixed a crash in `checkTokenRefreshPolicyWithIID:` and ensure `tokenWithAuthorizedEntity:scope:options:handler` method is refreshing token if token is not freshed any more. (#4167)
-- [changed] Updated deprecated keychain access level. (#4172)
-
-# 2019-10-22 -- 4.2.6
-- [fixed] Fixed InstanceID initialization timing issue (#4030).
-- [changed] Added check to see if token and IID are inconsistent (#4025).
-- [changed] Removed migration logic from document folder to application folder (#4033).
-
-# 2019-10-08 -- 4.2.5
-- [fixed] Fixed private header imports (#3796).
-
-# 2019-09-23 -- 4.2.4
-- [changed] Moved two headers from internal to private for Remote Config open sourcing (#3621).
-
-# 2019-08-20 -- 4.2.3
-- [fixed] Fixed a crash that could occur if InstanceID was shut down when fetching a new instance ID (#3439).
-
-# 2019-07-12 -- 4.2.2
-- [changed] Removed a call to a deprecated logging method (#3333).
-
-# 2019-07-09 -- 4.2.1
-- [fixed] Fixed an issue where fetching an instance ID wouldn't invoke the callback handler if the instance ID had not changed. (#3229)
-
-# 2019-06-18 -- 4.2.0
-- [added] Added macOS support for InstanceID (#2880)
-- [fixed] Corrected timezone proto key (#3132)
-
-# 2019-06-04 -- 4.1.1
-- [fixed] Fixed a crash in token fetching. Removed debug assertion that is only for develop build. (#3018)
-
-# 2019-05-21 -- 4.1.0
-- [fixed] Fixed a race condition where checkin was deleted before writing during app start, causing notifications to not be delivered correctly. (#2438)
-- [fixed] Fixed a keychain migration crash. (#2731)
-- [changed] Remove reflection call to get checkin info from Firebase Messaging. (#2825)
-
-# 2019-05-07 -- 4.0.0
-- [removed] Remove deprecated `token` method. Use `instanceIDWithHandler:` instead. (#2741)
-- [changed] Send `firebaseUserAgent` with a register request (#2679)
-
-# 2019-04-02 -- v3.8.1
-- [fixed] Fixed handling the multiple calls of instanceIDWithHandler. (#2445)
-- [fixed] Fixed a race condition where token kept getting refreshed at app start. (#2438)
-
-# 2019-03-19 -- v3.8.0
-- [added] Adding community support for tvOS. (#2428)
-- [added] Adding Firebase info to checkin. (#2509)
-- [fixed] Fixed a crash in FIRInstanceIDCheckinService. (#2548)
-
-# 2019-03-05 -- v3.7.0
-- [feature] Open source Firebase InstanceID. (#186)
-
-# 2019-02-20 -- v3.5.0
-- [changed] Always update keychain access control when adding new keychain to ensure it won't be blocked when device is locked. (#1399)
-
-# 2019-01-22 -- v3.4.0
-- [changed] Move all keychain write operations off the main thread. (#1399)
-- [changed] Make keychain operations asynchronous where possible (given the current APIs)
-- [changed] Avoid redundant keychain operations when it's been queried and cached before.
-
-# 2018-10-25 -- v3.3.0
-- [fixed] Fixed a crash caused by keychain operation when accessing default access group. (#1399, #1393)
-- [changed] Remove internal APIs that are no longer used.
-
-# 2018-09-25 -- v3.2.2
-- [fixed] Fixed a crash caused by NSUserDefaults being called on background thread.
-
-# 2018-08-14 -- v3.2.1
-- [fixed] Fixed an issue that checkin is not cached properly when app first started. (#1561)
-
-# 2018-07-31 -- v3.2.0
-- [added] Added support for global Firebase data collection flag. (#1219)
-- [changed] Improved message tracking sent by server API.
-- [fixed] Fixed an issue that InstanceID doesn't compile in app extensions, allowing its
-dependents like remote config to be working inside the app extensions.
-
-# 2018-06-19 -- v3.1.1
-- [fixed] Ensure the checkin and tokens are refreshed if firebase project changed.
-- [fixed] Fixed an issue that checkin should be turned off when FCM's autoInitEnabled flag is off.
-
-# 2018-06-12 -- v3.1.0
-- [added] Added a new API to fetch InstanceID and Token with a completion handler. The completion handler returns a FIRInstanceIDResult with a instanceID and a token properties.
-- [deprecated] Deprecated the token method.
-- [added] Added support to log a new customized label provided by developer.
-
-# 2018-05-08 -- v3.0.0
-- [removed] Removed deprecated method `setAPNSToken:type` defined in FIRInstanceID, please use `setAPNSToken:type` defined in FIRMessaging instead.
-- [removed] Removed deprecated enum `FIRInstanceIDAPNSTokenType` defined in FIRInstanceID, please use `FIRMessagingAPNSTokenType` defined in FIRMessaging instead.
-- [fixed] Fixed an issue that FCM scheduled messages were not tracked successfully.
-
-# 2018-03-06 -- v2.0.10
-- [changed] Improved documentation on InstanceID usage for GDPR.
-- [fixed] Improved the keypair handling during GCM to FCM migration. If you are migrating from GCM to FCM, we encourage you to update to this version and above.
-
-# 2018-02-06 -- v2.0.9
-- [fixed] Improved support for language targeting for FCM service. Server updates happen more efficiently when language changes.
-- [fixed] Improved support for FCM token auto generation enable/disable functions.
-
-# 2017-12-11 -- v2.0.8
-- [fixed] Fixed a crash caused by a reflection call during logging.
-- [changed] Updating server with the latest parameters and deprecating old ones.
-
-# 2017-11-27 -- v2.0.7
-- [fixed] Improve identity reset process, ensuring all information is reset during Identity deletion.
-
-# 2017-11-06 -- v2.0.6
-- [changed] Make token refresh weekly.
-- [fixed] Fixed a crash when performing token operation.
-
-# 2017-10-11 -- v2.0.5
-- [added] Improved support for working in shared Keychain environments.
-
-# 2017-09-26 -- v2.0.4
-- [fixed] Fixed an issue where the FCM token was not associating correctly with an APNs
-  device token, depending on when the APNs device token was made available.
-- [fixed] Fixed an issue where FCM tokens for different Sender IDs were not associating
-  correctly with an APNs device token.
-- [fixed] Fixed an issue that was preventing the FCM direct channel from being
-  established on the first start after 24 hours of being opened.
-
-# 2017-09-13 -- v2.0.3
-- [fixed] Fixed a race condition where a token was not being generated on first start,
-  if Firebase Messaging was included and the app did not register for remote
-  notifications.
-
-# 2017-08-25 -- v2.0.2
-- [fixed] Fixed a startup performance regression, removing a call which was blocking the
-  main thread.
-
-# 2017-08-07 -- v2.0.1
-- [fixed] Fixed issues with token and app identifier being inaccessible when the device
-  is locked.
-- [fixed] Fixed a crash if bundle identifier is nil, which is possible in some testing
-  environments.
-- [fixed] Fixed a small memory leak fetching a new token.
-- [changed] Moved to a new and simplified token storage system.
-- [changed] Moved to a new queuing system for token fetches and deletes.
-- [changed] Simplified logic and code around configuration and logging.
-- [changed] Added clarification about the 'apns_sandbox' parameter, in header comments.
-
-# 2017-05-08 -- v2.0.0
-- [added] Introduced an improved interface for Swift 3 developers
-- [deprecated] Deprecated some methods and properties after moving their logic to the
-  Firebase Cloud Messaging SDK
-- [fixed] Fixed an intermittent stability issue when a debug build of an app was
-  replaced with a release build of the same version
-- [fixed] Removed swizzling logic that was sometimes resulting in developers receiving
-  a validation notice about enabling push notification capabilities, even though
-  they weren't using push notifications
-- [fixed] Fixed a notification that would sometimes fire twice in quick succession
-  during the first run of an app
-
-# 2017-03-31 -- v1.0.10
-
-- [changed] Improvements to token-fetching logic
-- [fixed] Fixed some warnings in Instance ID
-- [fixed] Improved error messages if Instance ID couldn't be initialized properly
-- [fixed] Improvements to console logging
-
-# 2017-01-31 -- v1.0.9
-
-- [fixed] Removed an error being mistakenly logged to the console.
-
-# 2016-07-06 -- v1.0.8
-
-- [changed] Don't store InstanceID plists in Documents folder.
-
-# 2016-06-19 -- v1.0.7
-
-- [fixed] Fix remote-notifications warning on app submission.
-
-# 2016-05-16 -- v1.0.6
-
-- [fixed] Fix CocoaPod linter issues for InstanceID pod.
-
-# 2016-05-13 -- v1.0.5
-
-- [fixed] Fix Authorization errors for InstanceID tokens.
-
-# 2016-05-11 -- v1.0.4
-
-- [changed] Reduce wait for InstanceID token during parallel requests.
-
-# 2016-04-18 -- v1.0.3
-
-- [changed] Change flag to disable swizzling to *FirebaseAppDelegateProxyEnabled*.
-- [fixed] Fix incessant Keychain errors while accessing InstanceID.
-- [fixed] Fix max retries for fetching IID token.
-
-# 2016-04-18 -- v1.0.2
-
-- [changed] Register for remote notifications on iOS8+ in the SDK itself.

+ 0 - 147
Firebase/InstanceID/FIRIMessageCode.h

@@ -1,147 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-// The format of the debug code will show in the log as: e.g.
-// for code 1000, it will show as I-IID001000.
-typedef NS_ENUM(NSInteger, FIRInstanceIDMessageCode) {
-  // DO NOT USE 2000, 2002.
-  kFIRInstanceIDMessageCodeFIRApp000 = 1000,  // I-IID001000
-  kFIRInstanceIDMessageCodeFIRApp001 = 1001,
-  kFIRInstanceIDMessageCodeFIRApp002 = 1002,
-  kFIRInstanceIDMessageCodeInternal001 = 2001,
-  kFIRInstanceIDMessageCodeInternal002 = 2002,
-  // FIRInstanceID.m
-  // DO NOT USE 4000.
-  kFIRInstanceIDMessageCodeInstanceID000 = 3000,
-  kFIRInstanceIDMessageCodeInstanceID001 = 3001,
-  kFIRInstanceIDMessageCodeInstanceID002 = 3002,
-  kFIRInstanceIDMessageCodeInstanceID003 = 3003,
-  kFIRInstanceIDMessageCodeInstanceID004 = 3004,
-  kFIRInstanceIDMessageCodeInstanceID005 = 3005,
-  kFIRInstanceIDMessageCodeInstanceID006 = 3006,
-  kFIRInstanceIDMessageCodeInstanceID007 = 3007,
-  kFIRInstanceIDMessageCodeInstanceID008 = 3008,
-  kFIRInstanceIDMessageCodeInstanceID009 = 3009,
-  kFIRInstanceIDMessageCodeInstanceID010 = 3010,
-  kFIRInstanceIDMessageCodeInstanceID011 = 3011,
-  kFIRInstanceIDMessageCodeInstanceID012 = 3012,
-  kFIRInstanceIDMessageCodeInstanceID013 = 3013,
-  kFIRInstanceIDMessageCodeInstanceID014 = 3014,
-  kFIRInstanceIDMessageCodeInstanceID015 = 3015,
-  kFIRInstanceIDMessageCodeRefetchingTokenForAPNS = 3016,
-  kFIRInstanceIDMessageCodeInstanceID017 = 3017,
-  kFIRInstanceIDMessageCodeInstanceID018 = 3018,
-  // FIRInstanceIDAuthService.m
-  kFIRInstanceIDMessageCodeAuthService000 = 5000,
-  kFIRInstanceIDMessageCodeAuthService001 = 5001,
-  kFIRInstanceIDMessageCodeAuthService002 = 5002,
-  kFIRInstanceIDMessageCodeAuthService003 = 5003,
-  kFIRInstanceIDMessageCodeAuthService004 = 5004,
-  kFIRInstanceIDMessageCodeAuthServiceCheckinInProgress = 5004,
-
-  // FIRInstanceIDBackupExcludedPlist.m
-  // Do NOT USE 6003
-  kFIRInstanceIDMessageCodeBackupExcludedPlist000 = 6000,
-  kFIRInstanceIDMessageCodeBackupExcludedPlist001 = 6001,
-  kFIRInstanceIDMessageCodeBackupExcludedPlist002 = 6002,
-  // FIRInstanceIDCheckinService.m
-  kFIRInstanceIDMessageCodeService000 = 7000,
-  kFIRInstanceIDMessageCodeService001 = 7001,
-  kFIRInstanceIDMessageCodeService002 = 7002,
-  kFIRInstanceIDMessageCodeService003 = 7003,
-  kFIRInstanceIDMessageCodeService004 = 7004,
-  kFIRInstanceIDMessageCodeService005 = 7005,
-  kFIRInstanceIDMessageCodeService006 = 7006,
-  kFIRInstanceIDInvalidNetworkSession = 7007,
-  kFIRInstanceIDInvalidSettingResponse = 7008,
-  // FIRInstanceIDCheckinStore.m
-  // DO NOT USE 8002, 8004 - 8008
-  kFIRInstanceIDMessageCodeCheckinStore000 = 8000,
-  kFIRInstanceIDMessageCodeCheckinStore001 = 8001,
-  kFIRInstanceIDMessageCodeCheckinStore003 = 8003,
-  kFIRInstanceIDMessageCodeCheckinStoreCheckinPlistDeleted = 8009,
-  kFIRInstanceIDMessageCodeCheckinStoreCheckinPlistSaved = 8010,
-
-  // DO NOT USE 9000 - 9006
-
-  // DO NOT USE 10000 - 10009
-
-  // DO NOT USE 11000 - 11002
-
-  // DO NOT USE 12000 - 12014
-
-  // FIRInstanceIDStore.m
-  // DO NOT USE 13004, 13005, 13007, 13008, 13010, 13011, 13013, 13014
-  kFIRInstanceIDMessageCodeStore000 = 13000,
-  kFIRInstanceIDMessageCodeStore001 = 13001,
-  kFIRInstanceIDMessageCodeStore002 = 13002,
-  kFIRInstanceIDMessageCodeStore003 = 13003,
-  kFIRInstanceIDMessageCodeStore006 = 13006,
-  kFIRInstanceIDMessageCodeStore009 = 13009,
-  kFIRInstanceIDMessageCodeStore012 = 13012,
-  // FIRInstanceIDTokenManager.m
-  // DO NOT USE 14002, 14005
-  kFIRInstanceIDMessageCodeTokenManager000 = 14000,
-  kFIRInstanceIDMessageCodeTokenManager001 = 14001,
-  kFIRInstanceIDMessageCodeTokenManager003 = 14003,
-  kFIRInstanceIDMessageCodeTokenManager004 = 14004,
-  kFIRInstanceIDMessageCodeTokenManagerErrorDeletingFCMTokensOnAppReset = 14006,
-  kFIRInstanceIDMessageCodeTokenManagerDeletedFCMTokensOnAppReset = 14007,
-  kFIRInstanceIDMessageCodeTokenManagerSavedAppVersion = 14008,
-  kFIRInstanceIDMessageCodeTokenManagerErrorInvalidatingAllTokens = 14009,
-  kFIRInstanceIDMessageCodeTokenManagerAPNSChanged = 14010,
-  kFIRInstanceIDMessageCodeTokenManagerAPNSChangedTokenInvalidated = 14011,
-  kFIRInstanceIDMessageCodeTokenManagerInvalidateStaleToken = 14012,
-  // FIRInstanceIDTokenStore.m
-  // DO NOT USE 15002 - 15013
-  kFIRInstanceIDMessageCodeTokenStore000 = 15000,
-  kFIRInstanceIDMessageCodeTokenStore001 = 15001,
-  kFIRInstanceIDMessageCodeTokenStoreExceptionUnarchivingTokenInfo = 15015,
-
-  // DO NOT USE 16000, 18004
-
-  // FIRInstanceIDUtilities.m
-  kFIRInstanceIDMessageCodeUtilitiesMissingBundleIdentifier = 18000,
-  kFIRInstanceIDMessageCodeUtilitiesAppEnvironmentUtilNotAvailable = 18001,
-  kFIRInstanceIDMessageCodeUtilitiesCannotGetHardwareModel = 18002,
-  kFIRInstanceIDMessageCodeUtilitiesCannotGetSystemVersion = 18003,
-  // FIRInstanceIDTokenOperation.m
-  kFIRInstanceIDMessageCodeTokenOperationFailedToSignParams = 19000,
-  // FIRInstanceIDTokenFetchOperation.m
-  // DO NOT USE 20004, 20005
-  kFIRInstanceIDMessageCodeTokenFetchOperationFetchRequest = 20000,
-  kFIRInstanceIDMessageCodeTokenFetchOperationRequestError = 20001,
-  kFIRInstanceIDMessageCodeTokenFetchOperationBadResponse = 20002,
-  kFIRInstanceIDMessageCodeTokenFetchOperationBadTokenStructure = 20003,
-  // FIRInstanceIDTokenDeleteOperation.m
-  kFIRInstanceIDMessageCodeTokenDeleteOperationFetchRequest = 21000,
-  kFIRInstanceIDMessageCodeTokenDeleteOperationRequestError = 21001,
-  kFIRInstanceIDMessageCodeTokenDeleteOperationBadResponse = 21002,
-  // FIRInstanceIDTokenInfo.m
-  kFIRInstanceIDMessageCodeTokenInfoBadAPNSInfo = 22000,
-  kFIRInstanceIDMessageCodeTokenInfoFirebaseAppIDChanged = 22001,
-  kFIRInstanceIDMessageCodeTokenInfoLocaleChanged = 22002,
-  // FIRInstanceIDKeychain.m
-  kFIRInstanceIDKeychainReadItemError = 23000,
-  kFIRInstanceIDKeychainAddItemError = 23001,
-  kFIRInstanceIDKeychainDeleteItemError = 23002,
-  kFIRInstanceIDKeychainCreateKeyPairError = 23003,
-  kFIRInstanceIDKeychainUpdateItemError = 23004,
-
-  // DO NOT USE 24000, 24001
-};

+ 0 - 52
Firebase/InstanceID/FIRInstanceID+Private.m

@@ -1,52 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
-
-#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
-#import "Firebase/InstanceID/Private/FIRInstanceID_Private.h"
-
-@class FIRInstallations;
-
-@interface FIRInstanceID ()
-
-@property(nonatomic, readonly, strong) FIRInstanceIDTokenManager *tokenManager;
-
-@end
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-implementations"
-@implementation FIRInstanceID (Private)
-#pragma clang diagnostic pop
-
-// This method just wraps our pre-configured auth service to make the request.
-// This method is only needed by first-party users, like Remote Config.
-- (void)fetchCheckinInfoWithHandler:(FIRInstanceIDDeviceCheckinCompletion)handler {
-  [self.tokenManager.authService fetchCheckinInfoWithHandler:handler];
-}
-
-#pragma mark - Firebase Installations Compatibility
-
-/// Presence of this method indicates that this version of IID uses FirebaseInstallations under the
-/// hood. It is checked by FirebaseInstallations SDK.
-+ (BOOL)usesFIS {
-  return YES;
-}
-
-@end

+ 0 - 1164
Firebase/InstanceID/FIRInstanceID.m

@@ -1,1164 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/Public/FIRInstanceID.h"
-
-#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
-
-#import <GoogleUtilities/GULAppEnvironmentUtil.h>
-#import <GoogleUtilities/GULUserDefaults.h>
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-#import "Firebase/InstanceID/FIRInstanceIDCombinedHandler.h"
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDDefines.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-
-// Public constants
-NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
-
-#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
-const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
-    @"com.firebase.iid.notif.refresh-token";
-#else
-NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
-#endif  // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
-
-NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
-
-// Private constants
-int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60;  // 20 minutes
-int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10;       // 10 seconds
-// we retry only a max 5 times.
-// TODO(chliangGoogle): If we still fail we should listen for the network change notification
-// since GCM would have started Reachability. We only start retrying after we see a configuration
-// change.
-NSInteger const kMaxRetryCountForDefaultToken = 5;
-
-#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
-static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
-#else
-static NSString *const kEntitlementsAPSEnvironmentKey =
-    @"Entitlements.com.apple.developer.aps-environment";
-#endif
-static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
-/// FIRMessaging selector that returns the current FIRMessaging auto init
-/// enabled flag.
-static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled =
-    @"isAutoInitEnabledWithUserDefaults:";
-
-static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
-static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
-    @"FIRAppReadyToConfigureSDKNotification";
-static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
-static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
-static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
-
-/**
- *  The APNS token type for the app. If the token type is set to `UNKNOWN`
- *  InstanceID will implicitly try to figure out what the actual token type
- *  is from the provisioning profile.
- *  This must match FIRMessagingAPNSTokenType in FIRMessaging.h
- */
-typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
-  /// Unknown token type.
-  FIRInstanceIDAPNSTokenTypeUnknown,
-  /// Sandbox token type.
-  FIRInstanceIDAPNSTokenTypeSandbox,
-  /// Production token type.
-  FIRInstanceIDAPNSTokenTypeProd,
-} NS_SWIFT_NAME(InstanceIDAPNSTokenType);
-
-@interface FIRInstanceIDResult ()
-@property(nonatomic, readwrite, copy) NSString *instanceID;
-@property(nonatomic, readwrite, copy) NSString *token;
-@end
-
-@interface FIRInstanceID ()
-
-// FIRApp configuration objects.
-@property(nonatomic, readwrite, copy) NSString *fcmSenderID;
-@property(nonatomic, readwrite, copy) NSString *firebaseAppID;
-
-// Raw APNS token data
-@property(nonatomic, readwrite, strong) NSData *apnsTokenData;
-
-@property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
-// String-based, internal representation of APNS token
-@property(nonatomic, readwrite, copy) NSString *APNSTupleString;
-// Token fetched from the server automatically for the default app.
-@property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
-@property(nonatomic, readwrite, strong) FIRInstallations *installations;
-
-// backoff and retry for default token
-@property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
-@property(atomic, strong, nullable)
-    FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
-
-@end
-
-// InstanceID doesn't provide any functionality to other components,
-// so it provides a private, empty protocol that it conforms to and use it for registration.
-
-@protocol FIRInstanceIDInstanceProvider
-@end
-
-@interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
-@end
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-implementations"
-@implementation FIRInstanceIDResult
-#pragma clang diagnostic pop
-- (id)copyWithZone:(NSZone *)zone {
-  FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
-  result.instanceID = self.instanceID;
-  result.token = self.token;
-  return result;
-}
-@end
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-implementations"
-@implementation FIRInstanceID
-#pragma clang diagnostic pop
-
-// File static to support InstanceID tests that call [FIRInstanceID instanceID] after
-// [FIRInstanceID instanceIDForTests].
-static FIRInstanceID *gInstanceID;
-
-+ (instancetype)instanceID {
-  // If the static instance was created, return it. This should only be set in tests and we should
-  // eventually use proper dependency injection for a better test structure.
-  if (gInstanceID != nil) {
-    return gInstanceID;
-  }
-  FIRApp *defaultApp = [FIRApp defaultApp];  // Missing configure will be logged here.
-  FIRInstanceID *instanceID =
-      (FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
-  return instanceID;
-}
-
-- (instancetype)initPrivately {
-  self = [super init];
-  if (self != nil) {
-    // Use automatic detection of sandbox, unless otherwise set by developer
-    _apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
-  }
-  return self;
-}
-
-+ (FIRInstanceID *)instanceIDForTests {
-  gInstanceID = [[FIRInstanceID alloc] initPrivately];
-  [gInstanceID start];
-  return gInstanceID;
-}
-
-- (void)dealloc {
-  [[NSNotificationCenter defaultCenter] removeObserver:self];
-}
-
-#pragma mark - Tokens
-
-- (NSString *)token {
-  if (!self.fcmSenderID.length) {
-    return nil;
-  }
-
-  NSString *cachedToken = [self cachedTokenIfAvailable];
-
-  if (cachedToken) {
-    return cachedToken;
-  } else {
-    // If we've never had a cached default token, we should fetch one because unrelatedly,
-    // this request will help us determine whether the locally-generated Instance ID keypair is not
-    // unique, and therefore generate a new one.
-    [self defaultTokenWithHandler:nil];
-    return nil;
-  }
-}
-
-- (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
-  FIRInstanceID_WEAKIFY(self);
-  [self getIDWithHandler:^(NSString *identity, NSError *error) {
-    FIRInstanceID_STRONGIFY(self);
-    // This is in main queue already
-    if (error) {
-      if (handler) {
-        handler(nil, error);
-      }
-      return;
-    }
-    FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
-    result.instanceID = identity;
-    NSString *cachedToken = [self cachedTokenIfAvailable];
-    if (cachedToken) {
-      if (handler) {
-        result.token = cachedToken;
-        handler(result, nil);
-      }
-      // If no handler, simply return since client has generated iid and token.
-      return;
-    }
-    [self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
-      if (handler) {
-        if (error) {
-          handler(nil, error);
-          return;
-        }
-        result.token = token;
-        handler(result, nil);
-      }
-    }];
-  }];
-}
-
-- (NSString *)cachedTokenIfAvailable {
-  FIRInstanceIDTokenInfo *cachedTokenInfo =
-      [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
-                                                       scope:kFIRInstanceIDDefaultTokenScope];
-  return cachedTokenInfo.token;
-}
-
-- (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
-  // Sending this notification out will ensure that FIRMessaging and FIRInstanceID has the updated
-  // default FCM token.
-  // Only notify of token refresh if we have a new valid token that's different than before
-  if ((defaultFCMToken.length && _defaultFCMToken.length &&
-       ![defaultFCMToken isEqualToString:_defaultFCMToken]) ||
-      defaultFCMToken.length != _defaultFCMToken.length) {
-    NSNotification *tokenRefreshNotification =
-        [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
-                                      object:[defaultFCMToken copy]];
-    [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
-                                               postingStyle:NSPostASAP];
-  }
-
-  _defaultFCMToken = defaultFCMToken;
-}
-
-- (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
-                            scope:(NSString *)scope
-                          options:(NSDictionary *)options
-                          handler:(FIRInstanceIDTokenHandler)handler {
-  if (!handler) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
-                             kFIRInstanceIDInvalidNilHandlerError);
-    return;
-  }
-
-  // Add internal options
-  NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
-  if (options.count) {
-    [tokenOptions addEntriesFromDictionary:options];
-  }
-
-  NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
-  NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
-  if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
-    // APNS key was given, but server type is missing. Supply the server type with automatic
-    // checking. This can happen when the token is requested from FCM, which does not include a
-    // server type during its request.
-    tokenOptions[serverTypeKey] = @([self isSandboxApp]);
-  }
-  if (self.firebaseAppID) {
-    tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
-  }
-
-  // comparing enums to ints directly throws a warning
-  FIRInstanceIDErrorCode noError = INT_MAX;
-  FIRInstanceIDErrorCode errorCode = noError;
-  if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
-    errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
-  } else if (FIRInstanceIDIsValidGCMScope(scope) &&
-             ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
-  } else if (![authorizedEntity length]) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
-  } else if (![scope length]) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidScope;
-  } else if (!self.installations) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidStart;
-  }
-
-  FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
-    if (!error && [self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope]) {
-      // The local cache should be updated as it is critical for sending token updates.
-      self.defaultFCMToken = token;
-    }
-    dispatch_async(dispatch_get_main_queue(), ^{
-      handler(token, error);
-    });
-  };
-
-  if (errorCode != noError) {
-    newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
-    return;
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  FIRInstanceIDAuthService *authService = self.tokenManager.authService;
-  [authService fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
-                                             NSError *error) {
-    FIRInstanceID_STRONGIFY(self);
-    if (error) {
-      newHandler(nil, error);
-      return;
-    }
-
-    FIRInstanceID_WEAKIFY(self);
-    [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
-                                                       NSError *_Nullable error) {
-      FIRInstanceID_STRONGIFY(self);
-
-      if (error) {
-        NSError *newError =
-            [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
-        newHandler(nil, newError);
-
-      } else {
-        FIRInstanceIDTokenInfo *cachedTokenInfo =
-            [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
-        if (cachedTokenInfo) {
-          FIRInstanceIDAPNSInfo *optionsAPNSInfo =
-              [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
-          // Check if APNS Info is changed
-          if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
-              [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
-            // check if token is fresh
-            if ([cachedTokenInfo isFreshWithIID:identifier]) {
-              newHandler(cachedTokenInfo.token, nil);
-              return;
-            }
-          }
-        }
-        [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
-                                                       scope:[scope copy]
-                                                  instanceID:identifier
-                                                     options:tokenOptions
-                                                     handler:newHandler];
-      }
-    }];
-  }];
-}
-
-- (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
-                                  scope:(NSString *)scope
-                                handler:(FIRInstanceIDDeleteTokenHandler)handler {
-  if (!handler) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
-                             kFIRInstanceIDInvalidNilHandlerError);
-    return;
-  }
-
-  // comparing enums to ints directly throws a warning
-  FIRInstanceIDErrorCode noError = INT_MAX;
-  FIRInstanceIDErrorCode errorCode = noError;
-
-  if (![authorizedEntity length]) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
-  } else if (![scope length]) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidScope;
-  } else if (!self.installations) {
-    errorCode = kFIRInstanceIDErrorCodeInvalidStart;
-  }
-
-  FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
-    // If a default token is deleted successfully, reset the defaultFCMToken too.
-    if (!error) {
-      if ([self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope] ||
-          [authorizedEntity isEqualToString:@"*"]) {
-        self.defaultFCMToken = nil;
-      }
-    }
-    dispatch_async(dispatch_get_main_queue(), ^{
-      handler(error);
-    });
-  };
-
-  if (errorCode != noError) {
-    newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
-    return;
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  FIRInstanceIDAuthService *authService = self.tokenManager.authService;
-  [authService
-      fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
-        FIRInstanceID_STRONGIFY(self);
-        if (error) {
-          newHandler(error);
-          return;
-        }
-
-        FIRInstanceID_WEAKIFY(self);
-        [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
-                                                           NSError *_Nullable error) {
-          FIRInstanceID_STRONGIFY(self);
-          if (error) {
-            NSError *newError =
-                [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
-            newHandler(newError);
-
-          } else {
-            [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
-                                                         scope:scope
-                                                    instanceID:identifier
-                                                       handler:newHandler];
-          }
-        }];
-      }];
-}
-
-#pragma mark - Identity
-
-- (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
-  if (!handler) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
-                             kFIRInstanceIDInvalidNilHandlerError);
-    return;
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  [self.installations
-      installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
-        FIRInstanceID_STRONGIFY(self);
-        // When getID is explicitly called, trigger getToken to make sure token always exists.
-        // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
-        if (identifier) {
-          [self token];
-        }
-        handler(identifier, error);
-      }];
-}
-
-- (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
-  if (!handler) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
-                             kFIRInstanceIDInvalidNilHandlerError);
-    return;
-  }
-
-  void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
-    if ([NSThread isMainThread]) {
-      handler(error);
-      return;
-    }
-    dispatch_async(dispatch_get_main_queue(), ^{
-      handler(error);
-    });
-  };
-
-  if (!self.installations) {
-    FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
-    callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
-    return;
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
-    FIRInstanceID_STRONGIFY(self);
-    if (error) {
-      callHandlerOnMainThread(error);
-      return;
-    }
-    [self deleteIdentityWithHandler:^(NSError *error) {
-      callHandlerOnMainThread(error);
-    }];
-  };
-
-  [self.installations
-      installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
-        FIRInstanceID_STRONGIFY(self);
-        if (error) {
-          NSError *newError =
-              [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
-          callHandlerOnMainThread(newError);
-        } else {
-          [self.tokenManager deleteAllTokensWithInstanceID:identifier handler:deleteTokensHandler];
-        }
-      }];
-}
-
-- (void)notifyIdentityReset {
-  [self deleteIdentityWithHandler:nil];
-}
-
-// Delete all the local cache checkin, IID and token.
-- (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
-  // Delete tokens.
-  [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
-    // Reset FCM token.
-    self.defaultFCMToken = nil;
-    if (deleteTokenError) {
-      if (handler) {
-        handler(deleteTokenError);
-      }
-      return;
-    }
-
-    // Delete Instance ID.
-    [self.installations deleteWithCompletion:^(NSError *_Nullable error) {
-      if (error) {
-        if (handler) {
-          handler(error);
-        }
-        return;
-      }
-
-      [self deleteCheckinWithHandler:^(NSError *_Nullable error) {
-        if (error) {
-          if (handler) {
-            handler(error);
-          }
-          return;
-        }
-        // Only request new token if FCM auto initialization is
-        // enabled.
-        if ([self isFCMAutoInitEnabled]) {
-          // Deletion succeeds! Requesting new checkin, IID and token.
-          // TODO(chliangGoogle) see if dispatch_after is necessary
-          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
-                         dispatch_get_main_queue(), ^{
-                           [self defaultTokenWithHandler:nil];
-                         });
-        }
-        if (handler) {
-          handler(nil);
-        }
-      }];
-    }];
-  }];
-}
-
-#pragma mark - Checkin
-
-- (void)deleteCheckinWithHandler:(void (^)(NSError *error))handler {
-  [self.tokenManager.authService resetCheckinWithHandler:handler];
-}
-
-- (BOOL)tryToLoadValidCheckinInfo {
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [self.tokenManager.authService checkinPreferences];
-  return [checkinPreferences hasValidCheckinInfo];
-}
-
-- (NSString *)deviceAuthID {
-  return [self.tokenManager.authService checkinPreferences].deviceID;
-}
-
-- (NSString *)secretToken {
-  return [self.tokenManager.authService checkinPreferences].secretToken;
-}
-
-- (NSString *)versionInfo {
-  return [self.tokenManager.authService checkinPreferences].versionInfo;
-}
-
-#pragma mark - Config
-
-+ (void)load {
-  [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-iid"];
-}
-
-+ (nonnull NSArray<FIRComponent *> *)componentsToRegister {
-  FIRComponentCreationBlock creationBlock =
-      ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
-    // InstanceID only works with the default app.
-    if (!container.app.isDefaultApp) {
-      // Only configure for the default FIRApp.
-      FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
-                               @"Firebase Instance ID only works with the default app.");
-      return nil;
-    }
-
-    // Ensure it's cached so it returns the same instance every time instanceID is called.
-    *isCacheable = YES;
-    FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
-    [instanceID start];
-    [instanceID configureInstanceIDWithOptions:container.app.options];
-    return instanceID;
-  };
-  FIRComponent *instanceIDProvider =
-      [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
-                      instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
-                             dependencies:@[]
-                            creationBlock:creationBlock];
-  return @[ instanceIDProvider ];
-}
-
-- (void)configureInstanceIDWithOptions:(FIROptions *)options {
-  NSString *GCMSenderID = options.GCMSenderID;
-  if (!GCMSenderID.length) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
-                             @"Firebase not set up correctly, nil or empty senderID.");
-    [NSException raise:kFIRIIDErrorDomain
-                format:@"Could not configure Firebase InstanceID. GCMSenderID must not be nil or "
-                       @"empty."];
-  }
-
-  self.fcmSenderID = GCMSenderID;
-  self.firebaseAppID = options.googleAppID;
-
-  // FCM generates a FCM token during app start for sending push notification to device.
-  // This is not needed for app extension except for watch.
-#if TARGET_OS_WATCH
-  [self didCompleteConfigure];
-#else
-  if (![GULAppEnvironmentUtil isAppExtension]) {
-    [self didCompleteConfigure];
-  }
-#endif
-}
-
-// This is used to start any operations when we receive FirebaseSDK setup notification
-// from FIRCore.
-- (void)didCompleteConfigure {
-  NSString *cachedToken = [self cachedTokenIfAvailable];
-  // When there is a cached token, do the token refresh.
-  if (cachedToken) {
-    // Clean up expired tokens by checking the token refresh policy.
-    [self.installations
-        installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
-          if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier]) {
-            // Default token is expired, fetch default token from server.
-            [self defaultTokenWithHandler:nil];
-          }
-          // Notify FCM with the default token.
-          self.defaultFCMToken = [self token];
-        }];
-  } else if ([self isFCMAutoInitEnabled]) {
-    // When there is no cached token, must check auto init is enabled.
-    // If it's disabled, don't initiate token generation/refresh.
-    // If no cache token and auto init is enabled, fetch a token from server.
-    [self defaultTokenWithHandler:nil];
-    // Notify FCM with the default token.
-    self.defaultFCMToken = [self token];
-  }
-  // ONLY checkin when auto data collection is turned on.
-  if ([self isFCMAutoInitEnabled]) {
-    [self.tokenManager.authService scheduleCheckin:YES];
-  }
-}
-
-- (BOOL)isFCMAutoInitEnabled {
-  Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
-  // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
-  if (!messagingClass) {
-    return NO;
-  }
-
-  // Messaging doesn't have the class method, auto init should be enabled since FCM exists.
-  SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
-  if (![messagingClass respondsToSelector:autoInitSelector]) {
-    return YES;
-  }
-
-  // Get the autoInitEnabled class method.
-  IMP isAutoInitEnabledIMP = [messagingClass methodForSelector:autoInitSelector];
-  BOOL(*isAutoInitEnabled)
-  (Class, SEL, GULUserDefaults *) = (BOOL(*)(id, SEL, GULUserDefaults *))isAutoInitEnabledIMP;
-
-  // Check FCM's isAutoInitEnabled property.
-  return isAutoInitEnabled(messagingClass, autoInitSelector,
-                           [GULUserDefaults standardUserDefaults]);
-}
-
-// Actually makes InstanceID instantiate both the IID and Token-related subsystems.
-- (void)start {
-  if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
-    [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
-  }
-
-  [self setupTokenManager];
-  self.installations = [FIRInstallations installations];
-  [self setupNotificationListeners];
-}
-
-// Creates the token manager, which is used for fetching, caching, and retrieving tokens.
-- (void)setupTokenManager {
-  self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
-}
-
-- (void)setupNotificationListeners {
-  // To prevent double notifications remove observer from all events during setup.
-  NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-  [center removeObserver:self];
-  [center addObserver:self
-             selector:@selector(notifyIdentityReset)
-                 name:kFIRInstanceIDIdentityInvalidatedNotification
-               object:nil];
-  [center addObserver:self
-             selector:@selector(notifyAPNSTokenIsSet:)
-                 name:kFIRInstanceIDAPNSTokenNotification
-               object:nil];
-  [self observeFirebaseMessagingTokenChanges];
-}
-
-#pragma mark - Private Helpers
-/// Maximum retry count to fetch the default token.
-+ (int64_t)maxRetryCountForDefaultToken {
-  return kMaxRetryCountForDefaultToken;
-}
-
-/// Minimum interval in seconds between retries to fetch the default token.
-+ (int64_t)minIntervalForDefaultTokenRetry {
-  return kMinRetryIntervalForDefaultTokenInSeconds;
-}
-
-/// Maximum retry interval between retries to fetch default token.
-+ (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
-  return kMaxRetryIntervalForDefaultTokenInSeconds;
-}
-
-- (NSInteger)retryIntervalToFetchDefaultToken {
-  if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
-    return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
-  }
-  // exponential backoff with a fixed initial retry time
-  // 11s, 22s, 44s, 88s ...
-  int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
-  return (NSInteger)MIN(
-      (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
-      kMaxRetryIntervalForDefaultTokenInSeconds);
-}
-
-- (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
-  [self defaultTokenWithRetry:NO handler:aHandler];
-}
-
-/**
- * @param retry Indicates if the method is called to perform a retry after a failed attempt.
- * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
- * nil`
- */
-- (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
-  BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
-
-  if (!self.defaultTokenFetchHandler) {
-    self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
-  }
-
-  if (aHandler) {
-    [self.defaultTokenFetchHandler addHandler:aHandler];
-  }
-
-  if (!shouldPerformRequest) {
-    return;
-  }
-
-  NSDictionary *instanceIDOptions = @{};
-  BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
-  if (hasFirebaseMessaging) {
-    instanceIDOptions = [self defaultTokenOptions];
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
-    FIRInstanceID_STRONGIFY(self);
-
-    if (error) {
-      FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
-                               @"Failed to fetch default token %@", error);
-
-      // This notification can be sent multiple times since we can't guarantee success at any point
-      // of time.
-      NSNotification *tokenFetchFailNotification =
-          [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
-                                        object:[error copy]];
-      [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
-                                                 postingStyle:NSPostASAP];
-
-      self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
-                                                      [[self class] maxRetryCountForDefaultToken]);
-
-      // Do not retry beyond the maximum limit.
-      if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
-        NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
-        [self retryGetDefaultTokenAfter:retryInterval];
-      } else {
-        FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
-                                 @"Failed to retrieve the default FCM token after %ld retries",
-                                 (long)self.retryCountForDefaultToken);
-        [self performDefaultTokenHandlerWithToken:nil error:error];
-      }
-    } else {
-      // If somebody updated IID with APNS token while our initial request did not have it
-      // set we need to update it on the server.
-      NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
-      BOOL isSandboxInRequest =
-          [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
-      // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
-      NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
-          deviceTokenInRequest, isSandboxInRequest);
-      // If the APNs value either remained nil, or was the same non-nil value, the APNs value
-      // did not change.
-      BOOL APNSRemainedSameDuringFetch =
-          (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
-          ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
-      if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
-        // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
-        // value.
-        [self fetchNewToken];
-        FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
-                                 @"Received APNS token while fetching default token. "
-                                 @"Refetching default token. "
-                                 @"Updated cached APNS token: %@\n "
-                                 @"Stale request APNS token: %@",
-                                 self.APNSTupleString, APNSTupleStringInRequest);
-        // Do not notify and handle completion handler since this is a retry.
-        // Simply return.
-        return;
-      } else {
-        FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
-                                @"Successfully fetched default token.");
-      }
-      // Post the required notifications if somebody is waiting.
-      FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
-                               token);
-      // Update default FCM token, this method also triggers sending notification if token has
-      // changed.
-      self.defaultFCMToken = token;
-
-      [self performDefaultTokenHandlerWithToken:token error:nil];
-    }
-  };
-
-  [self tokenWithAuthorizedEntity:self.fcmSenderID
-                            scope:kFIRInstanceIDDefaultTokenScope
-                          options:instanceIDOptions
-                          handler:newHandler];
-}
-
-- (void)fetchNewToken {
-  [self.installations
-      installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
-        if (error) {
-          FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
-                                   kFIRInstanceIDInvalidNilHandlerError);
-        } else {
-          // The cached apns token has updated, recollect the default token options from cache.
-          [self.tokenManager fetchNewTokenWithAuthorizedEntity:self.fcmSenderID
-                                                         scope:kFIRInstanceIDDefaultTokenScope
-                                                    instanceID:identifier
-                                                       options:[self defaultTokenOptions]
-                                                       handler:nil];
-        }
-      }];
-}
-
-/**
- *
- */
-- (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
-  if (!self.defaultTokenFetchHandler) {
-    return;
-  }
-
-  [self.defaultTokenFetchHandler combinedHandler](token, error);
-  self.defaultTokenFetchHandler = nil;
-}
-
-- (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
-  FIRInstanceID_WEAKIFY(self);
-  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
-                 dispatch_get_main_queue(), ^{
-                   FIRInstanceID_STRONGIFY(self);
-                   // Pass nil: no new handlers to be added, currently existing handlers
-                   // will be called
-                   [self defaultTokenWithRetry:YES handler:nil];
-                 });
-}
-
-- (BOOL)isDefaultTokenWithAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope {
-  return [authorizedEntity isEqualToString:self.fcmSenderID] &&
-         [scope isEqualToString:kFIRInstanceIDDefaultTokenScope];
-}
-
-#pragma mark - APNS Token
-// This should only be triggered from FCM.
-- (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
-  NSData *token = notification.object;
-  if (!token || ![token isKindOfClass:[NSData class]]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
-                             NSStringFromClass([notification.object class]));
-    return;
-  }
-  NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
-
-  // The APNS token is being added, or has changed (rare)
-  if ([self.apnsTokenData isEqualToData:token]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
-                             @"Trying to reset APNS token to the same value. Will return");
-    return;
-  }
-  // Use this token type for when we have to automatically fetch tokens in the future
-  self.apnsTokenType = type;
-  BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
-  if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
-    isSandboxApp = [self isSandboxApp];
-  }
-  self.apnsTokenData = [token copy];
-  self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
-
-  // Pro-actively invalidate the default token, if the APNs change makes it
-  // invalid. Previously, we invalidated just before fetching the token.
-  NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
-      [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
-
-  // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
-  // they are up-to-date.
-  if (invalidatedTokens.count > 0) {
-    FIRInstanceID_WEAKIFY(self);
-
-    [self.installations
-        installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
-          FIRInstanceID_STRONGIFY(self);
-          if (self == nil) {
-            FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID017,
-                                     @"Instance ID shut down during token reset. Aborting");
-            return;
-          }
-          if (self.apnsTokenData == nil) {
-            FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID018,
-                                     @"apnsTokenData was set to nil during token reset. Aborting");
-            return;
-          }
-
-          NSMutableDictionary *tokenOptions = [@{
-            kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
-            kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
-          } mutableCopy];
-          if (self.firebaseAppID) {
-            tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
-          }
-
-          for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
-            if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
-              // We will perform a special fetch for the default FCM token, so that the delegate
-              // methods are called. For all others, we will do an internal re-fetch.
-              [self defaultTokenWithHandler:nil];
-            } else {
-              [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
-                                                             scope:tokenInfo.scope
-                                                        instanceID:identifier
-                                                           options:tokenOptions
-                                                           handler:^(NSString *_Nullable token,
-                                                                     NSError *_Nullable error){
-
-                                                           }];
-            }
-          }
-        }];
-  }
-}
-
-- (BOOL)isSandboxApp {
-  static BOOL isSandboxApp = YES;
-  static dispatch_once_t onceToken;
-  dispatch_once(&onceToken, ^{
-    isSandboxApp = ![self isProductionApp];
-  });
-  return isSandboxApp;
-}
-
-- (BOOL)isProductionApp {
-  const BOOL defaultAppTypeProd = YES;
-
-  NSError *error = nil;
-  if ([GULAppEnvironmentUtil isSimulator]) {
-    [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
-                                    @"Use prod profile by default."];
-    return defaultAppTypeProd;
-  }
-
-  if ([GULAppEnvironmentUtil isFromAppStore]) {
-    // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
-    return defaultAppTypeProd;
-  }
-#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
-  NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
-      stringByAppendingPathComponent:@"embedded.provisionprofile"];
-#elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
-  NSString *path = [[[NSBundle mainBundle] bundlePath]
-      stringByAppendingPathComponent:@"embedded.mobileprovision"];
-#endif
-
-  if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
-    // Distributed via TestFlight
-    return defaultAppTypeProd;
-  }
-
-  NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
-
-  if (!profileData.length || error) {
-    NSString *errorString =
-        [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
-    [self logAPNSConfigurationError:errorString];
-    return defaultAppTypeProd;
-  }
-
-  // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
-  // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
-  // ASCII. Replace any 0s or invalid characters in the input.
-  uint8_t *profileBytes = (uint8_t *)profileData.bytes;
-  for (int i = 0; i < profileData.length; i++) {
-    uint8_t currentByte = profileBytes[i];
-    if (!currentByte || currentByte > 127) {
-      profileBytes[i] = '.';
-    }
-  }
-
-  NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
-                                                             length:profileData.length
-                                                           encoding:NSASCIIStringEncoding
-                                                       freeWhenDone:NO];
-
-  if (error || !embeddedProfile.length) {
-    NSString *errorString =
-        [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
-    [self logAPNSConfigurationError:errorString];
-    return defaultAppTypeProd;
-  }
-
-  NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
-  NSString *plistContents;
-  if ([scanner scanUpToString:@"<plist" intoString:nil]) {
-    if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
-      plistContents = [plistContents stringByAppendingString:@"</plist>"];
-    }
-  }
-
-  if (!plistContents.length) {
-    return defaultAppTypeProd;
-  }
-
-  NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
-  if (!data.length) {
-    [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
-    return defaultAppTypeProd;
-  }
-
-  NSError *plistMapError;
-  id plistData = [NSPropertyListSerialization propertyListWithData:data
-                                                           options:NSPropertyListImmutable
-                                                            format:nil
-                                                             error:&plistMapError];
-  if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
-    NSString *errorString =
-        [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
-                                   plistMapError.localizedDescription];
-    [self logAPNSConfigurationError:errorString];
-    return defaultAppTypeProd;
-  }
-  NSDictionary *plistMap = (NSDictionary *)plistData;
-
-  if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
-                             @"Provisioning profile has specifically provisioned devices, "
-                             @"most likely a Dev profile.");
-  }
-
-  NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
-  NSString *debugString __unused =
-      [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
-
-  // No aps-environment in the profile.
-  if (!apsEnvironment.length) {
-    [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
-                                    @"correctly configured. Please recheck your provisioning "
-                                    @"profiles. If testing on a simulator this is fine since APNS "
-                                    @"doesn't work on the simulator."];
-    return defaultAppTypeProd;
-  }
-
-  if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
-    return NO;
-  }
-
-  return defaultAppTypeProd;
-}
-
-/// Log error messages only when Messaging exists in the pod.
-- (void)logAPNSConfigurationError:(NSString *)errorString {
-  BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
-  if (hasFirebaseMessaging) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
-  } else {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
-  }
-}
-
-- (void)observeFirebaseMessagingTokenChanges {
-  [[NSNotificationCenter defaultCenter]
-      removeObserver:self
-                name:kFIRInstanceIDMessagingUpdateTokenNotification
-              object:nil];
-  [[NSNotificationCenter defaultCenter]
-      addObserver:self
-         selector:@selector(messagingTokenDidChangeNotificationReceived:)
-             name:kFIRInstanceIDMessagingUpdateTokenNotification
-           object:nil];
-}
-
-- (void)messagingTokenDidChangeNotificationReceived:(NSNotification *)notification {
-  NSString *tokenUpdatedFromMessaging = notification.object;
-  if (!tokenUpdatedFromMessaging || [tokenUpdatedFromMessaging isKindOfClass:[NSString class]]) {
-    // Check the token from storage along with local value.
-    FIRInstanceIDTokenInfo *cachedTokenInfo =
-        [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
-                                                         scope:kFIRInstanceIDDefaultTokenScope];
-    NSString *cachedToken = cachedTokenInfo.token;
-
-    if (self.defaultFCMToken.length != tokenUpdatedFromMessaging.length ||
-        cachedToken.length != tokenUpdatedFromMessaging.length ||
-        (self.defaultFCMToken.length && tokenUpdatedFromMessaging.length &&
-         ![self.defaultFCMToken isEqualToString:tokenUpdatedFromMessaging]) ||
-        (cachedToken.length && tokenUpdatedFromMessaging.length &&
-         ![cachedToken isEqualToString:tokenUpdatedFromMessaging])) {
-      self.defaultFCMToken = tokenUpdatedFromMessaging;
-      [self.tokenManager saveDefaultToken:tokenUpdatedFromMessaging
-                              withOptions:[self defaultTokenOptions]];
-    }
-  }
-}
-
-- (NSDictionary *)defaultTokenOptions {
-  NSDictionary *tokenOptions = @{};
-  if (self.apnsTokenData) {
-    BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
-    if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
-      isSandboxApp = [self isSandboxApp];
-    }
-    tokenOptions = @{
-      kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
-      kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
-    };
-  }
-  return tokenOptions;
-}
-
-@end

+ 0 - 64
Firebase/InstanceID/FIRInstanceIDAPNSInfo.h

@@ -1,64 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-NS_ASSUME_NONNULL_BEGIN
-
-/**
- *  Represents an APNS device token and whether its environment is for sandbox.
- *  It can read from and write to an NSDictionary for simple serialization.
- */
-@interface FIRInstanceIDAPNSInfo : NSObject <NSCoding>
-
-/// The APNs device token, provided by the OS to the application delegate
-@property(nonatomic, readonly, strong) NSData *deviceToken;
-/// Represents whether or not this is deviceToken is for the sandbox
-/// environment, or production.
-@property(nonatomic, readonly, getter=isSandbox) BOOL sandbox;
-
-/**
- *  Initializes the receiver with an APNs device token, and boolean
- *  representing whether that token is for the sandbox environment.
- *
- *  @param deviceToken The APNs device token typically provided by the
- *         operating system.
- *  @param isSandbox   YES if the APNs device token is for the sandbox
- *                     environment, or NO if it is for production.
- *  @return An instance of FIRInstanceIDAPNSInfo.
- */
-- (instancetype)initWithDeviceToken:(NSData *)deviceToken isSandbox:(BOOL)isSandbox;
-
-/**
- *  Initializes the receiver from a token options dictionary containing data
- *  within the `kFIRInstanceIDTokenOptionsAPNSKey` and
- *  `kFIRInstanceIDTokenOptionsAPNSIsSandboxKey` keys. The token should be an
- *  NSData blob, and the sandbox value should be an NSNumber
- *  representing a boolean value.
- *
- *  @param dictionary A dictionary containing values under the keys
- *          `kFIRInstanceIDTokenOptionsAPNSKey` and
- *          `kFIRInstanceIDTokenOptionsAPNSIsSandboxKey`.
- *  @return An instance of FIRInstanceIDAPNSInfo, or nil if the
- *          dictionary data was invalid or missing.
- */
-- (nullable instancetype)initWithTokenOptionsDictionary:(NSDictionary *)dictionary;
-
-- (BOOL)isEqualToAPNSInfo:(FIRInstanceIDAPNSInfo *)otherInfo;
-
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 79
Firebase/InstanceID/FIRInstanceIDAPNSInfo.m

@@ -1,79 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDAPNSInfo.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-
-/// The key used to find the APNs device token in an archive.
-NSString *const kFIRInstanceIDAPNSInfoTokenKey = @"device_token";
-/// The key used to find the sandbox value in an archive.
-NSString *const kFIRInstanceIDAPNSInfoSandboxKey = @"sandbox";
-
-@implementation FIRInstanceIDAPNSInfo
-
-- (instancetype)initWithDeviceToken:(NSData *)deviceToken isSandbox:(BOOL)isSandbox {
-  self = [super init];
-  if (self) {
-    _deviceToken = [deviceToken copy];
-    _sandbox = isSandbox;
-  }
-  return self;
-}
-
-- (instancetype)initWithTokenOptionsDictionary:(NSDictionary *)dictionary {
-  id deviceToken = dictionary[kFIRInstanceIDTokenOptionsAPNSKey];
-  if (![deviceToken isKindOfClass:[NSData class]]) {
-    return nil;
-  }
-
-  id isSandbox = dictionary[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey];
-  if (![isSandbox isKindOfClass:[NSNumber class]]) {
-    return nil;
-  }
-  self = [super init];
-  if (self) {
-    _deviceToken = (NSData *)deviceToken;
-    _sandbox = ((NSNumber *)isSandbox).boolValue;
-  }
-  return self;
-}
-
-#pragma mark - NSCoding
-
-- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
-  id deviceToken = [aDecoder decodeObjectForKey:kFIRInstanceIDAPNSInfoTokenKey];
-  if (![deviceToken isKindOfClass:[NSData class]]) {
-    return nil;
-  }
-  BOOL isSandbox = [aDecoder decodeBoolForKey:kFIRInstanceIDAPNSInfoSandboxKey];
-  return [self initWithDeviceToken:(NSData *)deviceToken isSandbox:isSandbox];
-}
-
-- (void)encodeWithCoder:(NSCoder *)aCoder {
-  [aCoder encodeObject:self.deviceToken forKey:kFIRInstanceIDAPNSInfoTokenKey];
-  [aCoder encodeBool:self.sandbox forKey:kFIRInstanceIDAPNSInfoSandboxKey];
-}
-
-- (BOOL)isEqualToAPNSInfo:(FIRInstanceIDAPNSInfo *)otherInfo {
-  if ([super isEqual:otherInfo]) {
-    return YES;
-  }
-  return ([self.deviceToken isEqualToData:otherInfo.deviceToken] &&
-          self.isSandbox == otherInfo.isSandbox);
-}
-
-@end

+ 0 - 96
Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h

@@ -1,96 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-extern NSString *__nonnull const kFIRInstanceIDKeychainWildcardIdentifier;
-
-NS_ASSUME_NONNULL_BEGIN
-
-/**
- *  Wrapper around storing FCM auth data in iOS keychain.
- */
-@interface FIRInstanceIDAuthKeychain : NSObject
-
-/**
- *  Designated Initializer. Init a generic `SecClassGenericPassword` keychain with `identifier`
- *  as the `kSecAttrGeneric`.
- *
- *  @param identifier The generic attribute to be used by the keychain.
- *
- *  @return A Keychain object with `kSecAttrGeneric` attribute set to identifier.
- */
-- (instancetype)initWithIdentifier:(NSString *)identifier;
-
-/**
- *  Get keychain items matching the given service and account. The service and/or account
- *  can be a wildcard (`kFIRInstanceIDKeychainWildcardIdentifier`), which case the query
- *  will include all items matching any services and/or accounts.
- *
- *  @param service The kSecAttrService used to save the password. Can be wildcard.
- *  @param account The kSecAttrAccount used to save the password. Can be wildcard.
- *
- *  @return An array of |NSData|s matching the provided inputs.
- */
-- (NSArray<NSData *> *)itemsMatchingService:(NSString *)service account:(NSString *)account;
-
-/**
- *  Get keychain item for a given service and account.
- *
- *  @param service The kSecAttrService used to save the password.
- *  @param account The kSecAttrAccount used to save the password.
- *
- *  @return A cached keychain item for a given account and service, or nil if it was not
- *          found or could not be retrieved.
- */
-- (NSData *)dataForService:(NSString *)service account:(NSString *)account;
-
-/**
- *  Remove the cached items from the keychain matching the service, account and access group.
- *  In case the items do not exist, YES is returned but with a valid error object with code
- *  `errSecItemNotFound`.
- *
- *  @param service The kSecAttrService used to save the password.
- *  @param account The kSecAttrAccount used to save the password.
- *  @param handler The callback handler which is invoked when the remove operation is complete, with
- *                 an error if there is any.
- */
-- (void)removeItemsMatchingService:(NSString *)service
-                           account:(NSString *)account
-                           handler:(nullable void (^)(NSError *error))handler;
-
-/**
- *  Set the data for a given service and account.
- *  We use `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` which
- *  prevents backup and restore to iCloud, and works for app extension that can
- *  execute right after a device is restarted (and not unlocked).
- *
- *  @param data          The data to save.
- *  @param service       The `kSecAttrService` used to save the password.
- *  @param account       The `kSecAttrAccount` used to save the password.
- *  @param handler       The callback handler which is invoked when the add operation is complete,
- *                       with an error if there is any.
- *
- */
-- (void)setData:(NSData *)data
-     forService:(NSString *)service
-        account:(NSString *)account
-        handler:(nullable void (^)(NSError *))handler;
-
-- (void)setDataInCache:(NSData *)data forService:(NSString *)service account:(NSString *)account;
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 228
Firebase/InstanceID/FIRInstanceIDAuthKeyChain.m

@@ -1,228 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-#import "Firebase/InstanceID/FIRInstanceIDKeychain.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-
-/**
- *  The error type representing why we couldn't read data from the keychain.
- */
-typedef NS_ENUM(int, FIRInstanceIDKeychainErrorType) {
-  kFIRInstanceIDKeychainErrorBadArguments = -1301,
-};
-
-NSString *const kFIRInstanceIDKeychainWildcardIdentifier = @"*";
-
-@interface FIRInstanceIDAuthKeychain ()
-
-@property(nonatomic, copy) NSString *generic;
-// cachedKeychainData is keyed by service and account, the value is an array of NSData.
-// It is used to cache the tokens per service, per account, as well as checkin data per service,
-// per account inside the keychain.
-@property(nonatomic)
-    NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSArray<NSData *> *> *>
-        *cachedKeychainData;
-
-@end
-
-@implementation FIRInstanceIDAuthKeychain
-
-- (instancetype)initWithIdentifier:(NSString *)identifier {
-  self = [super init];
-  if (self) {
-    _generic = [identifier copy];
-    _cachedKeychainData = [[NSMutableDictionary alloc] init];
-  }
-  return self;
-}
-
-+ (NSMutableDictionary *)keychainQueryForService:(NSString *)service
-                                         account:(NSString *)account
-                                         generic:(NSString *)generic {
-  NSDictionary *query = @{(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword};
-
-  NSMutableDictionary *finalQuery = [NSMutableDictionary dictionaryWithDictionary:query];
-  if ([generic length] && ![kFIRInstanceIDKeychainWildcardIdentifier isEqualToString:generic]) {
-    finalQuery[(__bridge NSString *)kSecAttrGeneric] = generic;
-  }
-  if ([account length] && ![kFIRInstanceIDKeychainWildcardIdentifier isEqualToString:account]) {
-    finalQuery[(__bridge NSString *)kSecAttrAccount] = account;
-  }
-  if ([service length] && ![kFIRInstanceIDKeychainWildcardIdentifier isEqualToString:service]) {
-    finalQuery[(__bridge NSString *)kSecAttrService] = service;
-  }
-  return finalQuery;
-}
-
-- (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account {
-  return [[self class] keychainQueryForService:service account:account generic:self.generic];
-}
-
-- (NSArray<NSData *> *)itemsMatchingService:(NSString *)service account:(NSString *)account {
-  // If query wildcard service, it asks for all the results, which always query from keychain.
-  if (![service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier] &&
-      ![account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier] &&
-      _cachedKeychainData[service][account]) {
-    // As long as service, account array exist, even it's empty, it means we've queried it before,
-    // returns the cache value.
-    return _cachedKeychainData[service][account];
-  }
-
-  NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account];
-  NSMutableArray<NSData *> *results;
-  keychainQuery[(__bridge id)kSecReturnData] = (__bridge id)kCFBooleanTrue;
-#if TARGET_OS_IOS || TARGET_OS_TV
-  keychainQuery[(__bridge id)kSecReturnAttributes] = (__bridge id)kCFBooleanTrue;
-  keychainQuery[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitAll;
-  // FIRInstanceIDKeychain should only take a query and return a result, will handle the query here.
-  NSArray *passwordInfos =
-      CFBridgingRelease([[FIRInstanceIDKeychain sharedInstance] itemWithQuery:keychainQuery]);
-#elif TARGET_OS_OSX || TARGET_OS_WATCH
-  keychainQuery[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
-  NSData *passwordInfos =
-      CFBridgingRelease([[FIRInstanceIDKeychain sharedInstance] itemWithQuery:keychainQuery]);
-#endif
-
-  if (!passwordInfos) {
-    // Nothing was found, simply return from this sync block.
-    // Make sure to label the cache entry empty, signaling that we've queried this entry.
-    if ([service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier] ||
-        [account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-      // Do not update cache if it's wildcard query.
-      return @[];
-    } else if (_cachedKeychainData[service]) {
-      [_cachedKeychainData[service] setObject:@[] forKey:account];
-    } else {
-      [_cachedKeychainData setObject:[@{account : @[]} mutableCopy] forKey:service];
-    }
-    return @[];
-  }
-  results = [[NSMutableArray alloc] init];
-#if TARGET_OS_IOS || TARGET_OS_TV
-  NSInteger numPasswords = passwordInfos.count;
-  for (NSUInteger i = 0; i < numPasswords; i++) {
-    NSDictionary *passwordInfo = [passwordInfos objectAtIndex:i];
-    if (passwordInfo[(__bridge id)kSecValueData]) {
-      [results addObject:passwordInfo[(__bridge id)kSecValueData]];
-    }
-  }
-#elif TARGET_OS_OSX || TARGET_OS_WATCH
-  [results addObject:passwordInfos];
-#endif
-  // We query the keychain because it didn't exist in cache, now query is done, update the result in
-  // the cache.
-  if ([service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier] ||
-      [account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-    // Do not update cache if it's wildcard query.
-    return [results copy];
-  } else if (_cachedKeychainData[service]) {
-    [_cachedKeychainData[service] setObject:[results copy] forKey:account];
-  } else {
-    NSMutableDictionary *entry = [@{account : [results copy]} mutableCopy];
-    [_cachedKeychainData setObject:entry forKey:service];
-  }
-  return [results copy];
-}
-
-- (NSData *)dataForService:(NSString *)service account:(NSString *)account {
-  NSArray<NSData *> *items = [self itemsMatchingService:service account:account];
-  // If items is nil or empty, nil will be returned.
-  return items.firstObject;
-}
-
-- (void)removeItemsMatchingService:(NSString *)service
-                           account:(NSString *)account
-                           handler:(void (^)(NSError *error))handler {
-  if ([service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-    // Delete all keychain items.
-    _cachedKeychainData = [[NSMutableDictionary alloc] init];
-  } else if ([account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-    // Delete all entries under service,
-    if (_cachedKeychainData[service]) {
-      _cachedKeychainData[service] = [[NSMutableDictionary alloc] init];
-    }
-  } else if (_cachedKeychainData[service]) {
-    // We should keep the service/account entry instead of nil so we know
-    // it's "empty entry" instead of "not query from keychain yet".
-    [_cachedKeychainData[service] setObject:@[] forKey:account];
-  } else {
-    [_cachedKeychainData setObject:[@{account : @[]} mutableCopy] forKey:service];
-  }
-  NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account];
-  [[FIRInstanceIDKeychain sharedInstance] removeItemWithQuery:keychainQuery handler:handler];
-}
-
-- (void)setData:(NSData *)data
-     forService:(NSString *)service
-        account:(NSString *)account
-        handler:(void (^)(NSError *))handler {
-  if ([service isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier] ||
-      [account isEqualToString:kFIRInstanceIDKeychainWildcardIdentifier]) {
-    if (handler) {
-      handler([NSError errorWithDomain:kFIRInstanceIDKeychainErrorDomain
-                                  code:kFIRInstanceIDKeychainErrorBadArguments
-                              userInfo:nil]);
-    }
-    return;
-  }
-  [self removeItemsMatchingService:service
-                           account:account
-                           handler:^(NSError *error) {
-                             if (error) {
-                               if (handler) {
-                                 handler(error);
-                               }
-                               return;
-                             }
-                             if (data.length > 0) {
-                               NSMutableDictionary *keychainQuery =
-                                   [self keychainQueryForService:service account:account];
-                               keychainQuery[(__bridge id)kSecValueData] = data;
-
-                               keychainQuery[(__bridge id)kSecAttrAccessible] =
-                                   (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;
-                               [[FIRInstanceIDKeychain sharedInstance]
-                                   addItemWithQuery:keychainQuery
-                                            handler:handler];
-                             }
-                           }];
-  // Set the cache value. This must happen after removeItemsMatchingService:account:handler was
-  // called, so the cache value was reset before setting a new value.
-  if (_cachedKeychainData[service]) {
-    if (_cachedKeychainData[service][account]) {
-      _cachedKeychainData[service][account] = @[ data ];
-    } else {
-      [_cachedKeychainData[service] setObject:@[ data ] forKey:account];
-    }
-  } else {
-    [_cachedKeychainData setObject:[@{account : @[ data ]} mutableCopy] forKey:service];
-  }
-}
-
-- (void)setDataInCache:(NSData *)data forService:(NSString *)service account:(NSString *)account {
-  if (_cachedKeychainData[service]) {
-    if (_cachedKeychainData[service][account]) {
-      _cachedKeychainData[service][account] = @[ data ];
-    } else {
-      [_cachedKeychainData[service] setObject:@[ data ] forKey:account];
-    }
-  } else {
-    [_cachedKeychainData setObject:[@{account : @[ data ]} mutableCopy] forKey:service];
-  }
-}
-
-@end

+ 0 - 91
Firebase/InstanceID/FIRInstanceIDAuthService.h

@@ -1,91 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-
-@class FIRInstanceIDCheckinPreferences;
-@class FIRInstanceIDStore;
-
-/**
- *  FIRInstanceIDAuthService is responsible for retrieving, caching, and supplying checkin info
- *  for the rest of Instance ID. A checkin can be scheduled, meaning that it will keep retrying the
- *  checkin request until it is successful. A checkin can also be requested directly, with a
- *  completion handler.
- */
-@interface FIRInstanceIDAuthService : NSObject
-
-/**
- *  Used only for testing. In addition to taking a store (for locally caching the checkin info), it
- *  also takes a checkinService.
- */
-- (instancetype)initWithCheckinService:(FIRInstanceIDCheckinService *)checkinService
-                                 store:(FIRInstanceIDStore *)store;
-
-/**
- *  Initializes the auth service given a store (which provides the local caching of checkin info).
- *  This initializer will create its own instance of FIRInstanceIDCheckinService.
- */
-- (instancetype)initWithStore:(FIRInstanceIDStore *)store;
-
-#pragma mark - Checkin Service
-
-/**
- *  Checks if the current deviceID and secret are valid or not.
- *
- *  @return YES if the checkin credentials are valid else NO.
- */
-- (BOOL)hasValidCheckinInfo;
-
-/**
- *  Fetch checkin info from the server. This would usually refresh the existing
- *  checkin credentials for the current app.
- *
- *  @param handler The completion handler to invoke once the checkin info has been
- *                 refreshed.
- */
-- (void)fetchCheckinInfoWithHandler:(FIRInstanceIDDeviceCheckinCompletion)handler;
-
-/**
- *  Schedule checkin. Will hit the network only if the currently loaded checkin
- *  preferences are stale.
- *
- *  @param immediately YES if we want it to be scheduled immediately else NO.
- */
-- (void)scheduleCheckin:(BOOL)immediately;
-
-/**
- *  Returns the checkin preferences currently loaded in memory. The Checkin preferences
- *  can be either valid or invalid.
- *
- *  @return The checkin preferences loaded in memory.
- */
-- (FIRInstanceIDCheckinPreferences *)checkinPreferences;
-
-/**
- *  Cancels any ongoing checkin fetch, if any.
- */
-- (void)stopCheckinRequest;
-
-/**
- *  Resets the checkin information.
- *
- *  @param handler       The callback handler which is invoked when checkin reset is complete,
- *                       with an error if there is any.
- */
-- (void)resetCheckinWithHandler:(void (^)(NSError *error))handler;
-
-@end

+ 0 - 302
Firebase/InstanceID/FIRInstanceIDAuthService.m

@@ -1,302 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDDefines.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-// Max time interval between checkin retry in seconds.
-static const int64_t kMaxCheckinRetryIntervalInSeconds = 1 << 5;
-
-@interface FIRInstanceIDAuthService ()
-
-// Used to retrieve and cache the checkin info to disk and Keychain.
-@property(nonatomic, readwrite, strong) FIRInstanceIDStore *store;
-// Used to perform single checkin fetches.
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinService *checkinService;
-// The current checkin info. It will be compared to what is retrieved to determine whether it is
-// different than what is in the cache.
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinPreferences *checkinPreferences;
-
-// This array will track multiple handlers waiting for checkin to be performed. When a checkin
-// request completes, all the handlers will be notified.
-// Changes to the checkinHandlers array should happen in a thread-safe manner.
-@property(nonatomic, readonly, strong)
-    NSMutableArray<FIRInstanceIDDeviceCheckinCompletion> *checkinHandlers;
-
-// This is set to true if there is a checkin request in-flight.
-@property(atomic, readwrite, assign) BOOL isCheckinInProgress;
-// This timer is used a perform checkin retries. It is cancellable.
-@property(atomic, readwrite, strong) NSTimer *scheduledCheckinTimer;
-// The number of times checkin has been retried during a scheduled checkin.
-@property(atomic, readwrite, assign) int checkinRetryCount;
-
-@end
-
-@implementation FIRInstanceIDAuthService
-
-- (instancetype)initWithCheckinService:(FIRInstanceIDCheckinService *)checkinService
-                                 store:(FIRInstanceIDStore *)store {
-  self = [super init];
-  if (self) {
-    _store = store;
-    _checkinPreferences = [_store cachedCheckinPreferences];
-    _checkinService = checkinService;
-    _checkinHandlers = [NSMutableArray array];
-  }
-  return self;
-}
-
-- (void)dealloc {
-  [_scheduledCheckinTimer invalidate];
-}
-
-- (instancetype)initWithStore:(FIRInstanceIDStore *)store {
-  FIRInstanceIDCheckinService *checkinService = [[FIRInstanceIDCheckinService alloc] init];
-  return [self initWithCheckinService:checkinService store:store];
-}
-
-#pragma mark - Schedule Checkin
-
-- (void)scheduleCheckin:(BOOL)immediately {
-  // Checkin is still valid, so a remote checkin is not required.
-  if ([self.checkinPreferences hasValidCheckinInfo]) {
-    return;
-  }
-
-  // Checkin is already scheduled, so this (non-immediate) request can be ignored.
-  if (!immediately && [self.scheduledCheckinTimer isValid]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthService000,
-                             @"Checkin sync already scheduled. Will not schedule.");
-    return;
-  }
-
-  if (immediately) {
-    [self performScheduledCheckin];
-  } else {
-    int64_t checkinRetryDuration = [self calculateNextCheckinRetryIntervalInSeconds];
-    [self startCheckinTimerWithDuration:(NSTimeInterval)checkinRetryDuration];
-  }
-}
-
-- (void)startCheckinTimerWithDuration:(NSTimeInterval)timerDuration {
-  self.scheduledCheckinTimer =
-      [NSTimer scheduledTimerWithTimeInterval:timerDuration
-                                       target:self
-                                     selector:@selector(onScheduledCheckinTimerFired:)
-                                     userInfo:nil
-                                      repeats:NO];
-  // Add some tolerance to the timer, to allow iOS to be more flexible with this timer
-  self.scheduledCheckinTimer.tolerance = 0.5;
-}
-
-- (void)clearScheduledCheckinTimer {
-  [self.scheduledCheckinTimer invalidate];
-  self.scheduledCheckinTimer = nil;
-}
-
-- (void)onScheduledCheckinTimerFired:(NSTimer *)timer {
-  [self performScheduledCheckin];
-}
-
-- (void)performScheduledCheckin {
-  // No checkin scheduled as of now.
-  [self clearScheduledCheckinTimer];
-
-  // Checkin is still valid, so a remote checkin is not required.
-  if ([self.checkinPreferences hasValidCheckinInfo]) {
-    return;
-  }
-
-  FIRInstanceID_WEAKIFY(self);
-  [self
-      fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
-        FIRInstanceID_STRONGIFY(self);
-        self.checkinRetryCount++;
-
-        if (error) {
-          FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthService001, @"Checkin error %@.",
-                                   error);
-
-          dispatch_async(dispatch_get_main_queue(), ^{
-            // Schedule another checkin
-            [self scheduleCheckin:NO];
-          });
-
-        } else {
-          FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthService002, @"Checkin success.");
-        }
-      }];
-}
-
-- (int64_t)calculateNextCheckinRetryIntervalInSeconds {
-  // persistent failures can lead to overflow prevent that.
-  if (self.checkinRetryCount >= 10) {
-    return kMaxCheckinRetryIntervalInSeconds;
-  }
-  return MIN(1 << self.checkinRetryCount, kMaxCheckinRetryIntervalInSeconds);
-}
-
-#pragma mark - Checkin Service
-
-- (BOOL)hasValidCheckinInfo {
-  return [self.checkinPreferences hasValidCheckinInfo];
-}
-
-- (void)fetchCheckinInfoWithHandler:(nonnull FIRInstanceIDDeviceCheckinCompletion)handler {
-  // Perform any changes to self.checkinHandlers and _isCheckinInProgress in a thread-safe way.
-  @synchronized(self) {
-    [self.checkinHandlers addObject:handler];
-
-    if (_isCheckinInProgress) {
-      // Nothing more to do until our checkin request is done
-      FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthServiceCheckinInProgress,
-                               @"Checkin is in progress\n");
-      return;
-    }
-  }
-
-  // Checkin is still valid, so a remote checkin is not required.
-  if ([self.checkinPreferences hasValidCheckinInfo]) {
-    [self notifyCheckinHandlersWithCheckin:self.checkinPreferences error:nil];
-    return;
-  }
-
-  @synchronized(self) {
-    _isCheckinInProgress = YES;
-  }
-  [self.checkinService
-      checkinWithExistingCheckin:self.checkinPreferences
-                      completion:^(FIRInstanceIDCheckinPreferences *checkinPreferences,
-                                   NSError *error) {
-                        @synchronized(self) {
-                          self->_isCheckinInProgress = NO;
-                        }
-                        if (error) {
-                          FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthService003,
-                                                   @"Failed to checkin device %@", error);
-                          [self notifyCheckinHandlersWithCheckin:nil error:error];
-                          return;
-                        }
-
-                        FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeAuthService004,
-                                                 @"Successfully got checkin credentials");
-                        BOOL hasSameCachedPreferences =
-                            [self cachedCheckinMatchesCheckin:checkinPreferences];
-                        checkinPreferences.hasPreCachedAuthCredentials = hasSameCachedPreferences;
-
-                        // Update to the most recent checkin preferences
-                        self.checkinPreferences = checkinPreferences;
-
-                        // Save the checkin info to disk
-                        // Keychain might not be accessible, so confirm that checkin preferences can
-                        // be saved
-                        [self.store
-                            saveCheckinPreferences:checkinPreferences
-                                           handler:^(NSError *checkinSaveError) {
-                                             if (checkinSaveError && !hasSameCachedPreferences) {
-                                               // The checkin info was new, but it couldn't be
-                                               // written to the Keychain. Delete any stuff that was
-                                               // cached in memory. This doesn't delete any
-                                               // previously persisted preferences.
-                                               FIRInstanceIDLoggerError(
-                                                   kFIRInstanceIDMessageCodeService004,
-                                                   @"Unable to save checkin info, resetting "
-                                                   @"checkin preferences "
-                                                    "in memory.");
-                                               [checkinPreferences reset];
-                                               [self
-                                                   notifyCheckinHandlersWithCheckin:nil
-                                                                              error:
-                                                                                  checkinSaveError];
-                                             } else {
-                                               // The checkin is either new, or it was the same (and
-                                               // it couldn't be saved). Either way, report that the
-                                               // checkin preferences were received successfully.
-                                               [self notifyCheckinHandlersWithCheckin:
-                                                         checkinPreferences
-                                                                                error:nil];
-                                               if (!hasSameCachedPreferences) {
-                                                 // Checkin is new.
-                                                 // Notify any listeners that might be waiting for
-                                                 // checkin to be fetched, such as Firebase
-                                                 // Messaging (for its MCS connection).
-                                                 dispatch_async(dispatch_get_main_queue(), ^{
-                                                   [[NSNotificationCenter defaultCenter]
-                                                       postNotificationName:
-                                                           kFIRInstanceIDCheckinFetchedNotification
-                                                                     object:nil];
-                                                 });
-                                               }
-                                             }
-                                           }];
-                      }];
-}
-
-- (FIRInstanceIDCheckinPreferences *)checkinPreferences {
-  return _checkinPreferences;
-}
-
-- (void)stopCheckinRequest {
-  [self.checkinService stopFetching];
-}
-
-- (void)resetCheckinWithHandler:(void (^)(NSError *error))handler {
-  [self.store removeCheckinPreferencesWithHandler:^(NSError *error) {
-    if (!error) {
-      self.checkinPreferences = nil;
-    }
-    if (handler) {
-      handler(error);
-    }
-  }];
-}
-
-#pragma mark - Private
-
-/**
- *  Goes through the current list of checkin handlers and fires them with the same checkin and/or
- *  error info. The checkin handlers will get cleared after.
- */
-- (void)notifyCheckinHandlersWithCheckin:(nullable FIRInstanceIDCheckinPreferences *)checkin
-                                   error:(nullable NSError *)error {
-  @synchronized(self) {
-    for (FIRInstanceIDDeviceCheckinCompletion handler in self.checkinHandlers) {
-      handler(checkin, error);
-    }
-    [self.checkinHandlers removeAllObjects];
-  }
-}
-
-/**
- *  Given a |checkin|, it will compare it to the current checkinPreferences to see if the
- *  deviceID and secretToken are the same.
- */
-- (BOOL)cachedCheckinMatchesCheckin:(FIRInstanceIDCheckinPreferences *)checkin {
-  if (self.checkinPreferences && checkin) {
-    return ([self.checkinPreferences.deviceID isEqualToString:checkin.deviceID] &&
-            [self.checkinPreferences.secretToken isEqualToString:checkin.secretToken]);
-  }
-  return NO;
-}
-@end

+ 0 - 81
Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h

@@ -1,81 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-@interface FIRInstanceIDBackupExcludedPlist : NSObject
-
-/**
- *  Caches the plist contents in memory so we don't hit the disk each time we want
- *  to query something in the plist. This is loaded lazily i.e. if you write to the
- *  plist the contents you want to write will be stored here if the write was
- *  successful. The other case where it is loaded is if you read the plist contents
- *  by calling `contentAsDictionary`.
- *
- *  In case you write to the plist and then try to read the file using
- *  `contentAsDictionary` we would just return the cachedPlistContents since it would
- *  represent the disk contents.
- */
-@property(nonatomic, readonly, strong) NSDictionary *cachedPlistContents;
-
-/**
- *  Init a backup excluded plist file.
- *
- *  @param fileName                       The filename for the plist file.
- *  @param subDirectory The subdirectory in Application Support to save the plist.
- *
- *  @return Helper which allows to read write data to a backup excluded plist.
- */
-- (instancetype)initWithFileName:(NSString *)fileName subDirectory:(NSString *)subDirectory;
-
-/**
- *  Write dictionary data to the backup excluded plist file. If the file does not exist
- *  it would be created before writing to it.
- *
- *  @param dict  The data to be written to the plist.
- *  @param error The error object if any while writing the data.
- *
- *  @return YES if the write was successful else NO.
- */
-- (BOOL)writeDictionary:(NSDictionary *)dict error:(NSError **)error;
-
-/**
- *  Delete the backup excluded plist created with the above filename.
- *
- *  @param error The error object if any while deleting the file.
- *
- *  @return YES If the delete was successful else NO.
- */
-- (BOOL)deleteFile:(NSError **)error;
-
-/**
- *  The contents of the plist file. We also store the contents of the file in-memory.
- *  If the in-memory contents are valid we return the in-memory contents else we read
- *  the file from disk.
- *
- *  @return A dictionary object that contains the contents of the plist file if the file
- *          exists else nil.
- */
-- (NSDictionary *)contentAsDictionary;
-
-/**
- *  Check if the plist exists on the disk or not.
- *
- *  @return YES if the file exists on the disk else NO.
- */
-- (BOOL)doesFileExist;
-
-@end

+ 0 - 117
Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.m

@@ -1,117 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-
-@interface FIRInstanceIDBackupExcludedPlist ()
-
-@property(nonatomic, readwrite, copy) NSString *fileName;
-@property(nonatomic, readwrite, copy) NSString *subDirectoryName;
-@property(nonatomic, readwrite, strong) NSDictionary *cachedPlistContents;
-
-@end
-
-@implementation FIRInstanceIDBackupExcludedPlist
-
-- (instancetype)initWithFileName:(NSString *)fileName subDirectory:(NSString *)subDirectory {
-  self = [super init];
-  if (self) {
-    _fileName = [fileName copy];
-    _subDirectoryName = [subDirectory copy];
-  }
-  return self;
-}
-
-- (BOOL)writeDictionary:(NSDictionary *)dict error:(NSError **)error {
-  NSString *path = [self plistPathInDirectory];
-  if (![dict writeToFile:path atomically:YES]) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeBackupExcludedPlist000,
-                             @"Failed to write to %@.plist", self.fileName);
-    return NO;
-  }
-
-  // Successfully wrote contents -- change the in-memory contents
-  self.cachedPlistContents = [dict copy];
-
-  NSURL *URL = [NSURL fileURLWithPath:path];
-  if (error) {
-    *error = nil;
-  }
-
-  NSDictionary *preferences = [URL resourceValuesForKeys:@[ NSURLIsExcludedFromBackupKey ]
-                                                   error:error];
-  if ([preferences[NSURLIsExcludedFromBackupKey] boolValue]) {
-    return YES;
-  }
-
-  BOOL success = [URL setResourceValue:@(YES) forKey:NSURLIsExcludedFromBackupKey error:error];
-  if (!success) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeBackupExcludedPlist001,
-                             @"Error excluding %@ from backup, %@", [URL lastPathComponent],
-                             error ? *error : @"");
-  }
-  return success;
-}
-
-- (BOOL)deleteFile:(NSError **)error {
-  BOOL success = YES;
-  NSString *path = [self plistPathInDirectory];
-  if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
-    success = [[NSFileManager defaultManager] removeItemAtPath:path error:error];
-  }
-  // remove the in-memory contents
-  self.cachedPlistContents = nil;
-  return success;
-}
-
-- (NSDictionary *)contentAsDictionary {
-  if (!self.cachedPlistContents) {
-    NSString *path = [self plistPathInDirectory];
-    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
-      self.cachedPlistContents = [[NSDictionary alloc] initWithContentsOfFile:path];
-    }
-  }
-  return self.cachedPlistContents;
-}
-
-- (BOOL)doesFileExist {
-  NSString *path = [self plistPathInDirectory];
-  return [[NSFileManager defaultManager] fileExistsAtPath:path];
-}
-
-#pragma mark - Private
-
-- (NSString *)plistPathInDirectory {
-  NSArray *directoryPaths;
-  NSString *plistNameWithExtension = [NSString stringWithFormat:@"%@.plist", self.fileName];
-  directoryPaths =
-      NSSearchPathForDirectoriesInDomains([self supportedDirectory], NSUserDomainMask, YES);
-  NSArray *components = @[ directoryPaths.lastObject, _subDirectoryName, plistNameWithExtension ];
-
-  return [NSString pathWithComponents:components];
-}
-
-- (NSSearchPathDirectory)supportedDirectory {
-#if TARGET_OS_TV
-  return NSCachesDirectory;
-#else
-  return NSApplicationSupportDirectory;
-#endif
-}
-
-@end

+ 0 - 64
Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h

@@ -1,64 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-@interface FIRInstanceIDCheckinPreferences (Internal)
-
-/**
- *  Parse the checkin auth credentials saved in the Keychain to initialize checkin
- *  preferences.
- *
- *  @param keychainContent The checkin auth credentials saved in the Keychain.
- *
- *  @return A valid checkin preferences object if the checkin auth credentials in the
- *          keychain can be parsed successfully else nil.
- */
-+ (FIRInstanceIDCheckinPreferences *)preferencesFromKeychainContents:(NSString *)keychainContent;
-
-/**
- *  Default initializer for InstanceID checkin preferences.
- *
- *  @param deviceID    The deviceID for the app.
- *  @param secretToken The secret token the app uses to authenticate with the server.
- *
- *  @return A checkin preferences object with given deviceID and secretToken.
- */
-- (instancetype)initWithDeviceID:(NSString *)deviceID secretToken:(NSString *)secretToken;
-
-/**
- *  Update checkin preferences from the preferences dict persisted as a plist. The dict contains
- *  all the checkin preferences retrieved from the server except the deviceID and secret which
- *  are stored in the Keychain.
- *
- *  @param checkinPlistContent The checkin preferences saved in a plist on the disk.
- */
-- (void)updateWithCheckinPlistContents:(NSDictionary *)checkinPlistContent;
-
-/**
- *  Reset the current checkin preferences object.
- */
-- (void)reset;
-
-/**
- *  The string that contains the checkin auth credentials i.e. deviceID and secret. This
- *  needs to be stored in the Keychain.
- *
- *  @return The checkin auth credential string containing the deviceID and secret.
- */
-- (NSString *)checkinKeychainContent;
-
-@end

+ 0 - 112
Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.m

@@ -1,112 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-
-static NSString *const kCheckinKeychainContentSeparatorString = @"|";
-
-@interface FIRInstanceIDCheckinPreferences ()
-
-@property(nonatomic, readwrite, copy) NSString *deviceID;
-@property(nonatomic, readwrite, copy) NSString *secretToken;
-@property(nonatomic, readwrite, copy) NSString *digest;
-@property(nonatomic, readwrite, copy) NSString *versionInfo;
-@property(nonatomic, readwrite, copy) NSString *deviceDataVersion;
-
-@property(nonatomic, readwrite, strong) NSMutableDictionary *gServicesData;
-@property(nonatomic, readwrite, assign) int64_t lastCheckinTimestampMillis;
-
-@end
-
-@implementation FIRInstanceIDCheckinPreferences (Internal)
-
-+ (FIRInstanceIDCheckinPreferences *)preferencesFromKeychainContents:(NSString *)keychainContent {
-  NSString *deviceID = [self checkinDeviceIDFromKeychainContent:keychainContent];
-  NSString *secret = [self checkinSecretFromKeychainContent:keychainContent];
-  if ([deviceID length] && [secret length]) {
-    return [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:deviceID secretToken:secret];
-  } else {
-    return nil;
-  }
-}
-
-- (instancetype)initWithDeviceID:(NSString *)deviceID secretToken:(NSString *)secretToken {
-  self = [super init];
-  if (self) {
-    self.deviceID = [deviceID copy];
-    self.secretToken = [secretToken copy];
-  }
-  return self;
-}
-
-- (void)reset {
-  self.deviceID = nil;
-  self.secretToken = nil;
-  self.digest = nil;
-  self.versionInfo = nil;
-  self.gServicesData = nil;
-  self.deviceDataVersion = nil;
-  self.lastCheckinTimestampMillis = 0;
-}
-
-- (void)updateWithCheckinPlistContents:(NSDictionary *)checkinPlistContent {
-  for (NSString *key in checkinPlistContent) {
-    if ([kFIRInstanceIDDigestStringKey isEqualToString:key]) {
-      self.digest = [checkinPlistContent[key] copy];
-    } else if ([kFIRInstanceIDVersionInfoStringKey isEqualToString:key]) {
-      self.versionInfo = [checkinPlistContent[key] copy];
-    } else if ([kFIRInstanceIDLastCheckinTimeKey isEqualToString:key]) {
-      self.lastCheckinTimestampMillis = [checkinPlistContent[key] longLongValue];
-    } else if ([kFIRInstanceIDGServicesDictionaryKey isEqualToString:key]) {
-      self.gServicesData = [checkinPlistContent[key] mutableCopy];
-    } else if ([kFIRInstanceIDDeviceDataVersionKey isEqualToString:key]) {
-      self.deviceDataVersion = [checkinPlistContent[key] copy];
-    }
-    // Otherwise we have some keys we don't care about
-  }
-}
-
-- (NSString *)checkinKeychainContent {
-  if ([self.deviceID length] && [self.secretToken length]) {
-    return [NSString stringWithFormat:@"%@%@%@", self.deviceID,
-                                      kCheckinKeychainContentSeparatorString, self.secretToken];
-  } else {
-    return nil;
-  }
-}
-
-+ (NSString *)checkinDeviceIDFromKeychainContent:(NSString *)keychainContent {
-  return [self checkinKeychainContent:keychainContent forIndex:0];
-}
-
-+ (NSString *)checkinSecretFromKeychainContent:(NSString *)keychainContent {
-  return [self checkinKeychainContent:keychainContent forIndex:1];
-}
-
-+ (NSString *)checkinKeychainContent:(NSString *)keychainContent forIndex:(int)index {
-  NSArray *keychainComponents =
-      [keychainContent componentsSeparatedByString:kCheckinKeychainContentSeparatorString];
-  if (index >= 0 && index < 2 && [keychainComponents count] == 2) {
-    return keychainComponents[index];
-  } else {
-    return nil;
-  }
-}
-
-@end

+ 0 - 95
Firebase/InstanceID/FIRInstanceIDCheckinPreferences.m

@@ -1,95 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-#import <GoogleUtilities/GULUserDefaults.h>
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-
-const NSTimeInterval kFIRInstanceIDDefaultCheckinInterval = 7 * 24 * 60 * 60;  // 7 days.
-
-@interface FIRInstanceIDCheckinPreferences ()
-
-@property(nonatomic, readwrite, copy) NSString *deviceID;
-@property(nonatomic, readwrite, copy) NSString *secretToken;
-@property(nonatomic, readwrite, copy) NSString *digest;
-@property(nonatomic, readwrite, copy) NSString *versionInfo;
-@property(nonatomic, readwrite, copy) NSString *deviceDataVersion;
-
-@property(nonatomic, readwrite, strong) NSMutableDictionary *gServicesData;
-@property(nonatomic, readwrite, assign) int64_t lastCheckinTimestampMillis;
-
-// This flag indicates that we have already saved the above deviceID and secret
-// to our keychain and hence we don't need to save again. This is helpful since
-// on checkin refresh we can avoid writing to the Keychain which can sometimes
-// be very buggy. For info check this https://forums.developer.apple.com/thread/4743
-@property(nonatomic, readwrite, assign) BOOL hasPreCachedAuthCredentials;
-
-@end
-
-@implementation FIRInstanceIDCheckinPreferences
-
-- (NSDictionary *)checkinPlistContents {
-  NSMutableDictionary *checkinPlistContents = [NSMutableDictionary dictionary];
-  checkinPlistContents[kFIRInstanceIDDigestStringKey] = self.digest ?: @"";
-  checkinPlistContents[kFIRInstanceIDVersionInfoStringKey] = self.versionInfo ?: @"";
-  checkinPlistContents[kFIRInstanceIDDeviceDataVersionKey] = self.deviceDataVersion ?: @"";
-  checkinPlistContents[kFIRInstanceIDLastCheckinTimeKey] = @(self.lastCheckinTimestampMillis);
-  checkinPlistContents[kFIRInstanceIDGServicesDictionaryKey] =
-      [self.gServicesData count] ? self.gServicesData : @{};
-  return checkinPlistContents;
-}
-
-- (BOOL)hasCheckinInfo {
-  return (self.deviceID.length && self.secretToken.length);
-}
-
-- (BOOL)hasValidCheckinInfo {
-  int64_t currentTimestampInMillis = FIRInstanceIDCurrentTimestampInMilliseconds();
-  int64_t timeSinceLastCheckinInMillis = currentTimestampInMillis - self.lastCheckinTimestampMillis;
-
-  BOOL hasCheckinInfo = [self hasCheckinInfo];
-  NSString *lastLocale =
-      [[GULUserDefaults standardUserDefaults] stringForKey:kFIRInstanceIDUserDefaultsKeyLocale];
-  // If it's app's first time open and checkin is already fetched and no locale information is
-  // stored, then checkin info is valid. We should not checkin again because locale is considered
-  // "changed".
-  if (hasCheckinInfo && !lastLocale) {
-    NSString *currentLocale = FIRInstanceIDCurrentLocale();
-    [[GULUserDefaults standardUserDefaults] setObject:currentLocale
-                                               forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-    return YES;
-  }
-
-  // If locale has changed, checkin info is no longer valid.
-  // Also update locale information if changed. (Only do it here not in token refresh)
-  if (FIRInstanceIDHasLocaleChanged()) {
-    NSString *currentLocale = FIRInstanceIDCurrentLocale();
-    [[GULUserDefaults standardUserDefaults] setObject:currentLocale
-                                               forKey:kFIRInstanceIDUserDefaultsKeyLocale];
-    return NO;
-  }
-
-  return (hasCheckinInfo &&
-          (timeSinceLastCheckinInMillis / 1000.0 < kFIRInstanceIDDefaultCheckinInterval));
-}
-
-- (void)setHasPreCachedAuthCredentials:(BOOL)hasPreCachedAuthCredentials {
-  _hasPreCachedAuthCredentials = hasPreCachedAuthCredentials;
-}
-
-@end

+ 0 - 27
Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h

@@ -1,27 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-/** Checkin refresh interval. **/
-FOUNDATION_EXPORT const NSTimeInterval kFIRInstanceIDDefaultCheckinInterval;
-
-@interface FIRInstanceIDCheckinPreferences ()
-
-- (BOOL)hasPreCachedAuthCredentials;
-- (void)setHasPreCachedAuthCredentials:(BOOL)hasPreCachedAuthCredentials;
-
-@end

+ 0 - 68
Firebase/InstanceID/FIRInstanceIDCheckinService.h

@@ -1,68 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
-
-NS_ASSUME_NONNULL_BEGIN
-
-// keys in Checkin preferences
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDDeviceAuthIdKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDSecretTokenKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDDigestStringKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDLastCheckinTimeKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDVersionInfoStringKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDGServicesDictionaryKey;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDDeviceDataVersionKey;
-
-@class FIRInstanceIDCheckinPreferences;
-
-/**
- *  Register the device with Checkin Service and get back the `authID`, `secret
- *  token` etc. for the client. Checkin results are cached in the
- *  `FIRInstanceIDCache` and periodically refreshed to prevent them from being stale.
- *  Each client needs to register with checkin before registering with InstanceID.
- */
-@interface FIRInstanceIDCheckinService : NSObject
-
-/**
- *  Execute a device checkin request to obtain an deviceID, secret token,
- *  gService data.
- *
- *  @param existingCheckin An existing checkin preference object, if available.
- *  @param completion Completion hander called on success or failure of device checkin.
- */
-- (void)checkinWithExistingCheckin:(nullable FIRInstanceIDCheckinPreferences *)existingCheckin
-                        completion:(FIRInstanceIDDeviceCheckinCompletion)completion;
-
-/**
- *  This would stop any request that the service made to the checkin backend and also
- *  release any callback handlers that it holds.
- */
-- (void)stopFetching;
-
-/**
- *  Set test block for mock testing network requests.
- *
- *  @param block The block to invoke as a mock response from the network.
- */
-+ (void)setCheckinTestBlock:(nullable FIRInstanceIDURLRequestTestBlock)block;
-
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 242
Firebase/InstanceID/FIRInstanceIDCheckinService.m

@@ -1,242 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDDefines.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-
-static NSString *const kDeviceCheckinURL = @"https://device-provisioning.googleapis.com/checkin";
-
-// keys in Checkin preferences
-NSString *const kFIRInstanceIDDeviceAuthIdKey = @"GMSInstanceIDDeviceAuthIdKey";
-NSString *const kFIRInstanceIDSecretTokenKey = @"GMSInstanceIDSecretTokenKey";
-NSString *const kFIRInstanceIDDigestStringKey = @"GMSInstanceIDDigestKey";
-NSString *const kFIRInstanceIDLastCheckinTimeKey = @"GMSInstanceIDLastCheckinTimestampKey";
-NSString *const kFIRInstanceIDVersionInfoStringKey = @"GMSInstanceIDVersionInfo";
-NSString *const kFIRInstanceIDGServicesDictionaryKey = @"GMSInstanceIDGServicesData";
-NSString *const kFIRInstanceIDDeviceDataVersionKey = @"GMSInstanceIDDeviceDataVersion";
-
-static NSUInteger const kCheckinType = 2;  // DeviceType IOS in l/w/a/_checkin.proto
-static NSUInteger const kCheckinVersion = 2;
-static NSUInteger const kFragment = 0;
-
-static FIRInstanceIDURLRequestTestBlock testBlock;
-
-@interface FIRInstanceIDCheckinService ()
-
-@property(nonatomic, readwrite, strong) NSURLSession *session;
-
-@end
-
-@implementation FIRInstanceIDCheckinService
-;
-
-- (instancetype)init {
-  self = [super init];
-  if (self) {
-    // Create an URLSession once, even though checkin should happen about once a day
-    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
-    config.timeoutIntervalForResource = 60.0f;  // 1 minute
-    config.allowsCellularAccess = YES;
-    _session = [NSURLSession sessionWithConfiguration:config];
-    _session.sessionDescription = @"com.google.iid-checkin";
-  }
-  return self;
-}
-
-- (void)dealloc {
-  testBlock = nil;
-  [self.session invalidateAndCancel];
-}
-
-- (void)checkinWithExistingCheckin:(FIRInstanceIDCheckinPreferences *)existingCheckin
-                        completion:(FIRInstanceIDDeviceCheckinCompletion)completion {
-  if (self.session == nil) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDInvalidNetworkSession,
-                             @"Inconsistent state: NSURLSession has been invalidated");
-    NSError *error =
-        [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeRegistrarFailedToCheckIn];
-    if (completion) {
-      completion(nil, error);
-    }
-    return;
-  }
-
-  NSURL *url = [NSURL URLWithString:kDeviceCheckinURL];
-  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
-  [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
-  NSDictionary *checkinParameters = [self checkinParametersWithExistingCheckin:existingCheckin];
-  NSData *checkinData = [NSJSONSerialization dataWithJSONObject:checkinParameters
-                                                        options:0
-                                                          error:nil];
-  request.HTTPMethod = @"POST";
-  request.HTTPBody = checkinData;
-
-  void (^handler)(NSData *, NSURLResponse *, NSError *) =
-      ^(NSData *data, NSURLResponse *response, NSError *error) {
-        if (error) {
-          FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService000,
-                                   @"Device checkin HTTP fetch error. Error Code: %ld",
-                                   (long)error.code);
-          if (completion) {
-            completion(nil, error);
-          }
-          return;
-        }
-
-        NSError *serializationError;
-        NSDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data
-                                                                     options:0
-                                                                       error:&serializationError];
-        if (serializationError) {
-          FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService001,
-                                   @"Error serializing json object. Error Code: %ld",
-                                   _FIRInstanceID_L(serializationError.code));
-          if (completion) {
-            completion(nil, serializationError);
-          }
-          return;
-        }
-
-        NSString *deviceAuthID = [dataResponse[@"android_id"] stringValue];
-        NSString *secretToken = [dataResponse[@"security_token"] stringValue];
-        if ([deviceAuthID length] == 0) {
-          NSError *error =
-              [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidRequest];
-          if (completion) {
-            completion(nil, error);
-          }
-          return;
-        }
-
-        int64_t lastCheckinTimestampMillis = [dataResponse[@"time_msec"] longLongValue];
-        int64_t currentTimestampMillis = FIRInstanceIDCurrentTimestampInMilliseconds();
-        // Somehow the server clock gets out of sync with the device clock.
-        // Reset the last checkin timestamp in case this happens.
-        if (lastCheckinTimestampMillis > currentTimestampMillis) {
-          FIRInstanceIDLoggerDebug(
-              kFIRInstanceIDMessageCodeService002, @"Invalid last checkin timestamp %@ in future.",
-              [NSDate dateWithTimeIntervalSince1970:lastCheckinTimestampMillis / 1000.0]);
-          lastCheckinTimestampMillis = currentTimestampMillis;
-        }
-
-        NSString *deviceDataVersionInfo = dataResponse[@"device_data_version_info"] ?: @"";
-        NSString *digest = dataResponse[@"digest"] ?: @"";
-
-        FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService003,
-                                 @"Checkin successful with authId: %@, "
-                                 @"digest: %@, "
-                                 @"lastCheckinTimestamp: %lld",
-                                 deviceAuthID, digest, lastCheckinTimestampMillis);
-
-        NSString *versionInfo = dataResponse[@"version_info"] ?: @"";
-        NSMutableDictionary *gservicesData = [NSMutableDictionary dictionary];
-
-        // Read gServices data.
-        NSArray *flatSettings = dataResponse[@"setting"];
-        for (NSDictionary *dict in flatSettings) {
-          if (dict[@"name"] && dict[@"value"]) {
-            gservicesData[dict[@"name"]] = dict[@"value"];
-          } else {
-            FIRInstanceIDLoggerDebug(kFIRInstanceIDInvalidSettingResponse,
-                                     @"Invalid setting in checkin response: (%@: %@)",
-                                     dict[@"name"], dict[@"value"]);
-          }
-        }
-
-        FIRInstanceIDCheckinPreferences *checkinPreferences =
-            [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:deviceAuthID
-                                                          secretToken:secretToken];
-        NSDictionary *preferences = @{
-          kFIRInstanceIDDigestStringKey : digest,
-          kFIRInstanceIDVersionInfoStringKey : versionInfo,
-          kFIRInstanceIDLastCheckinTimeKey : @(lastCheckinTimestampMillis),
-          kFIRInstanceIDGServicesDictionaryKey : gservicesData,
-          kFIRInstanceIDDeviceDataVersionKey : deviceDataVersionInfo,
-        };
-        [checkinPreferences updateWithCheckinPlistContents:preferences];
-        if (completion) {
-          completion(checkinPreferences, nil);
-        }
-      };
-  // Test block
-  if (testBlock) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService005,
-                             @"Test block set, will not hit the server");
-    testBlock(request, handler);
-    return;
-  }
-
-  NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:handler];
-  [task resume];
-}
-
-- (void)stopFetching {
-  [self.session invalidateAndCancel];
-  // The session cannot be reused after invalidation. Dispose it to prevent accident reusing.
-  self.session = nil;
-}
-
-#pragma mark - Private
-
-- (NSDictionary *)checkinParametersWithExistingCheckin:
-    (nullable FIRInstanceIDCheckinPreferences *)checkinPreferences {
-  NSString *deviceModel = FIRInstanceIDDeviceModel();
-  NSString *systemVersion = FIRInstanceIDOperatingSystemVersion();
-  NSString *osVersion = [NSString stringWithFormat:@"IOS_%@", systemVersion];
-
-  // Get locale from GCM if GCM exists else use system API.
-  NSString *locale = FIRInstanceIDCurrentLocale();
-
-  NSInteger userNumber = 0;        // Multi Profile may change this.
-  NSInteger userSerialNumber = 0;  // Multi Profile may change this
-
-  NSString *timeZone = [NSTimeZone localTimeZone].name;
-  int64_t lastCheckingTimestampMillis = checkinPreferences.lastCheckinTimestampMillis;
-
-  NSDictionary *checkinParameters = @{
-    @"checkin" : @{
-      @"iosbuild" : @{@"model" : deviceModel, @"os_version" : osVersion},
-      @"type" : @(kCheckinType),
-      @"user_number" : @(userNumber),
-      @"last_checkin_msec" : @(lastCheckingTimestampMillis),
-    },
-    @"fragment" : @(kFragment),
-    @"locale" : locale,
-    @"version" : @(kCheckinVersion),
-    @"digest" : checkinPreferences.digest ?: @"",
-    @"time_zone" : timeZone,
-    @"user_serial_number" : @(userSerialNumber),
-    @"id" : @([checkinPreferences.deviceID longLongValue]),
-    @"security_token" : @([checkinPreferences.secretToken longLongValue]),
-  };
-
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService006, @"Checkin parameters: %@",
-                           checkinParameters);
-  return checkinParameters;
-}
-
-+ (void)setCheckinTestBlock:(FIRInstanceIDURLRequestTestBlock)block {
-  testBlock = [block copy];
-}
-
-@end

+ 0 - 96
Firebase/InstanceID/FIRInstanceIDCheckinStore.h

@@ -1,96 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-@class FIRInstanceIDAuthKeychain;
-@class FIRInstanceIDBackupExcludedPlist;
-@class FIRInstanceIDCheckinPreferences;
-
-// These values exposed for testing
-extern NSString *const kFIRInstanceIDCheckinKeychainService;
-
-/**
- *  Checkin preferences backing store.
- */
-@interface FIRInstanceIDCheckinStore : NSObject
-
-/**
- *  Designated Initializer. Initialize a checkin store with the given backup excluded
- *  plist filename.
- *
- *  @param checkinFilename                The backup excluded plist filename to persist checkin
- *                                        preferences.
- *
- *  @param subDirectoryName               Sub-directory in standard directory where we write
- *                                        InstanceID plist.
- *
- *  @return Store to persist checkin preferences.
- */
-- (instancetype)initWithCheckinPlistFileName:(NSString *)checkinFilename
-                            subDirectoryName:(NSString *)subDirectoryName;
-
-/**
- *  Initialize a checkin store with the given backup excluded  plist and keychain.
- *
- *  @param plist        The backup excluded plist to persist checkin preferences.
- *  @param keychain     The keychain used to persist checkin auth preferences.
- *
- *  @return Store to persist checkin preferences.
- */
-- (instancetype)initWithCheckinPlist:(FIRInstanceIDBackupExcludedPlist *)plist
-                            keychain:(FIRInstanceIDAuthKeychain *)keychain;
-
-/**
- *  Checks whether the backup excluded checkin preferences are present on the disk or not.
- *
- *  @return YES if the backup excluded checkin plist exists on the disks else NO.
- */
-- (BOOL)hasCheckinPlist;
-
-#pragma mark - Save
-
-/**
- *  Save the checkin preferences to backing store.
- *
- *  @param preferences   Checkin preferences to save.
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- */
-- (void)saveCheckinPreferences:(FIRInstanceIDCheckinPreferences *)preferences
-                       handler:(void (^)(NSError *error))handler;
-
-#pragma mark - Delete
-
-/**
- *  Remove the cached checkin preferences.
- *
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- */
-- (void)removeCheckinPreferencesWithHandler:(void (^)(NSError *error))handler;
-
-#pragma mark - Get
-
-/**
- *  Get the cached device secret. If we cannot access it for some reason we
- *  return the appropriate error object.
- *
- *  @return The cached checkin preferences if present else nil.
- */
-- (FIRInstanceIDCheckinPreferences *)cachedCheckinPreferences;
-
-@end

+ 0 - 193
Firebase/InstanceID/FIRInstanceIDCheckinStore.m

@@ -1,193 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
-#import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences_Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDCheckinService.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-
-static NSString *const kFIRInstanceIDCheckinKeychainGeneric = @"com.google.iid";
-
-NSString *const kFIRInstanceIDCheckinKeychainService = @"com.google.iid.checkin";
-
-@interface FIRInstanceIDCheckinStore ()
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDBackupExcludedPlist *plist;
-@property(nonatomic, readwrite, strong) FIRInstanceIDAuthKeychain *keychain;
-// Checkin will store items under
-// Keychain account: <app bundle id>,
-// Keychain service: |kFIRInstanceIDCheckinKeychainService|
-@property(nonatomic, readonly) NSString *bundleIdentifierForKeychainAccount;
-
-@end
-
-@implementation FIRInstanceIDCheckinStore
-
-- (instancetype)initWithCheckinPlistFileName:(NSString *)checkinFilename
-                            subDirectoryName:(NSString *)subDirectoryName {
-  FIRInstanceIDBackupExcludedPlist *plist =
-      [[FIRInstanceIDBackupExcludedPlist alloc] initWithFileName:checkinFilename
-                                                    subDirectory:subDirectoryName];
-
-  FIRInstanceIDAuthKeychain *keychain =
-      [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDCheckinKeychainGeneric];
-  return [self initWithCheckinPlist:plist keychain:keychain];
-}
-
-- (instancetype)initWithCheckinPlist:(FIRInstanceIDBackupExcludedPlist *)plist
-                            keychain:(FIRInstanceIDAuthKeychain *)keychain {
-  self = [super init];
-  if (self) {
-    _plist = plist;
-    _keychain = keychain;
-  }
-  return self;
-}
-
-- (BOOL)hasCheckinPlist {
-  return [self.plist doesFileExist];
-}
-
-- (NSString *)bundleIdentifierForKeychainAccount {
-  static NSString *bundleIdentifier;
-  static dispatch_once_t onceToken;
-  dispatch_once(&onceToken, ^{
-    bundleIdentifier = FIRInstanceIDAppIdentifier();
-  });
-  return bundleIdentifier;
-}
-
-- (void)saveCheckinPreferences:(FIRInstanceIDCheckinPreferences *)preferences
-                       handler:(void (^)(NSError *error))handler {
-  NSDictionary *checkinPlistContents = [preferences checkinPlistContents];
-  NSString *checkinKeychainContent = [preferences checkinKeychainContent];
-
-  if (![checkinKeychainContent length]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeCheckinStore000,
-                             @"Failed to get checkin keychain content from memory.");
-    if (handler) {
-      handler([NSError
-          errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeRegistrarFailedToCheckIn]);
-    }
-    return;
-  }
-  if (![checkinPlistContents count]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeCheckinStore001,
-                             @"Failed to get checkin plist contents from memory.");
-    if (handler) {
-      handler([NSError
-          errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeRegistrarFailedToCheckIn]);
-    }
-    return;
-  }
-
-  // Save all other checkin preferences in a plist
-  NSError *error;
-  if (![self.plist writeDictionary:checkinPlistContents error:&error]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeCheckinStore003,
-                             @"Failed to save checkin plist contents."
-                             @"Will delete auth credentials");
-    [self.keychain removeItemsMatchingService:kFIRInstanceIDCheckinKeychainService
-                                      account:self.bundleIdentifierForKeychainAccount
-                                      handler:nil];
-    if (handler) {
-      handler(error);
-    }
-    return;
-  }
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeCheckinStoreCheckinPlistSaved,
-                           @"Checkin plist file is saved");
-
-  // Save the deviceID and secret in the Keychain
-  if (!preferences.hasPreCachedAuthCredentials) {
-    NSData *data = [checkinKeychainContent dataUsingEncoding:NSUTF8StringEncoding];
-    [self.keychain setData:data
-                forService:kFIRInstanceIDCheckinKeychainService
-                   account:self.bundleIdentifierForKeychainAccount
-                   handler:^(NSError *error) {
-                     if (error) {
-                       if (handler) {
-                         handler(error);
-                       }
-                       return;
-                     }
-                     if (handler) {
-                       handler(nil);
-                     }
-                   }];
-  } else {
-    handler(nil);
-  }
-}
-
-- (void)removeCheckinPreferencesWithHandler:(void (^)(NSError *error))handler {
-  // Delete the checkin preferences plist first to avoid delay.
-  NSError *deletePlistError;
-  if (![self.plist deleteFile:&deletePlistError]) {
-    handler(deletePlistError);
-    return;
-  }
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeCheckinStoreCheckinPlistDeleted,
-                           @"Deleted checkin plist file.");
-  // Remove deviceID and secret from Keychain
-  [self.keychain removeItemsMatchingService:kFIRInstanceIDCheckinKeychainService
-                                    account:self.bundleIdentifierForKeychainAccount
-                                    handler:^(NSError *error) {
-                                      handler(error);
-                                    }];
-}
-
-- (FIRInstanceIDCheckinPreferences *)cachedCheckinPreferences {
-  // Query the keychain for deviceID and secret
-  NSData *item = [self.keychain dataForService:kFIRInstanceIDCheckinKeychainService
-                                       account:self.bundleIdentifierForKeychainAccount];
-
-  // Check info found in keychain
-  NSString *checkinKeychainContent = [[NSString alloc] initWithData:item
-                                                           encoding:NSUTF8StringEncoding];
-  FIRInstanceIDCheckinPreferences *checkinPreferences =
-      [FIRInstanceIDCheckinPreferences preferencesFromKeychainContents:checkinKeychainContent];
-
-  NSDictionary *checkinPlistContents = [self.plist contentAsDictionary];
-
-  NSString *plistDeviceAuthID = checkinPlistContents[kFIRInstanceIDDeviceAuthIdKey];
-  NSString *plistSecretToken = checkinPlistContents[kFIRInstanceIDSecretTokenKey];
-
-  // If deviceID and secret not found in the keychain verify that we don't have them in the
-  // checkin preferences plist.
-  if (![checkinPreferences.deviceID length] && ![checkinPreferences.secretToken length]) {
-    if ([plistDeviceAuthID length] && [plistSecretToken length]) {
-      // Couldn't find checkin credentials in keychain but found them in the plist.
-      checkinPreferences =
-          [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:plistDeviceAuthID
-                                                        secretToken:plistSecretToken];
-    } else {
-      // Couldn't find checkin credentials in keychain nor plist
-      return nil;
-    }
-  }
-
-  [checkinPreferences updateWithCheckinPlistContents:checkinPlistContents];
-  return checkinPreferences;
-}
-
-@end

+ 0 - 31
Firebase/InstanceID/FIRInstanceIDCombinedHandler.h

@@ -1,31 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-NS_ASSUME_NONNULL_BEGIN
-
-/**
- * A generic class to combine several handler blocks into a single block in a thread-safe manner
- */
-@interface FIRInstanceIDCombinedHandler<ResultType> : NSObject
-
-- (void)addHandler:(void (^)(ResultType _Nullable result, NSError* _Nullable error))handler;
-- (void (^)(ResultType _Nullable result, NSError* _Nullable error))combinedHandler;
-
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 64
Firebase/InstanceID/FIRInstanceIDCombinedHandler.m

@@ -1,64 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDCombinedHandler.h"
-
-NS_ASSUME_NONNULL_BEGIN
-
-typedef void (^FIRInstanseIDHandler)(id _Nullable result, NSError *_Nullable error);
-
-@interface FIRInstanceIDCombinedHandler <ResultType>()
-@property(atomic, readonly, strong) NSMutableArray<FIRInstanseIDHandler> *handlers;
-@end
-
-NS_ASSUME_NONNULL_END
-
-@implementation FIRInstanceIDCombinedHandler
-
-- (instancetype)init {
-  self = [super init];
-  if (self) {
-    _handlers = [NSMutableArray array];
-  }
-  return self;
-}
-
-- (void)addHandler:(FIRInstanseIDHandler)handler {
-  if (!handler) {
-    return;
-  }
-
-  @synchronized(self) {
-    [self.handlers addObject:handler];
-  }
-}
-
-- (FIRInstanseIDHandler)combinedHandler {
-  FIRInstanseIDHandler combinedHandler = nil;
-
-  @synchronized(self) {
-    NSArray<FIRInstanseIDHandler> *handlers = [self.handlers copy];
-    combinedHandler = ^(id result, NSError *error) {
-      for (FIRInstanseIDHandler handler in handlers) {
-        handler(result, error);
-      }
-    };
-  }
-
-  return combinedHandler;
-}
-
-@end

+ 0 - 65
Firebase/InstanceID/FIRInstanceIDConstants.h

@@ -1,65 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-#pragma mark - Commands
-
-/**
- *  Value included in a structured response or GCM message from IID, indicating
- *  an identity reset.
- */
-FOUNDATION_EXPORT NSString *const kFIRInstanceID_CMD_RST;
-
-#pragma mark - Notifications
-
-/// Notification used to deliver GCM messages for InstanceID.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDCheckinFetchedNotification;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDAPNSTokenNotification;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDDefaultGCMTokenFailNotification;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDMessagingUpdateTokenNotification;
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDIdentityInvalidatedNotification;
-
-#pragma mark - Miscellaneous
-
-/// The scope used to save the IID "*" scope token. This is used for saving the
-/// IID auth token that we receive from the server. This feature was never
-/// implemented on the server side.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDAllScopeIdentifier;
-/// The scope used to save the IID "*" scope token.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDDefaultTokenScope;
-
-/// Subdirectory in search path directory to store InstanceID preferences.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDSubDirectoryName;
-
-/// The key for APNS token in options dictionary.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDTokenOptionsAPNSKey;
-
-/// The key for APNS token environment type in options dictionary.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
-
-/// The key for GMP AppID sent in registration requests.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDTokenOptionsFirebaseAppIDKey;
-
-/// The key to enable auto-register by swizzling AppDelegate's methods.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDAppDelegateProxyEnabledInfoPlistKey;
-
-/// The key for InstallationID or InstanceID in token request.
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDParamInstanceID;
-
-/// Error code for missing entitlements in Keychain. iOS Keychain error
-/// https://forums.developer.apple.com/thread/4743
-FOUNDATION_EXPORT const int kFIRInstanceIDSecMissingEntitlementErrorCode;

+ 0 - 47
Firebase/InstanceID/FIRInstanceIDConstants.m

@@ -1,47 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-
-// Commands
-NSString *const kFIRInstanceID_CMD_RST = @"RST";
-
-// NOTIFICATIONS
-NSString *const kFIRInstanceIDCheckinFetchedNotification = @"com.google.gcm.notif-checkin-fetched";
-NSString *const kFIRInstanceIDAPNSTokenNotification = @"com.firebase.iid.notif.apns-token";
-NSString *const kFIRInstanceIDDefaultGCMTokenFailNotification =
-    @"com.firebase.iid.notif.fcm-token-fail";
-NSString *const kFIRInstanceIDMessagingUpdateTokenNotification =
-    @"com.firebase.messaging.notif.fcm-token-refreshed";
-NSString *const kFIRInstanceIDIdentityInvalidatedNotification = @"com.google.iid.identity-invalid";
-
-// Miscellaneous
-NSString *const kFIRInstanceIDAllScopeIdentifier = @"iid-all";
-NSString *const kFIRInstanceIDDefaultTokenScope = @"*";
-NSString *const kFIRInstanceIDSubDirectoryName = @"Google/FirebaseInstanceID";
-
-// Registration Options
-NSString *const kFIRInstanceIDTokenOptionsAPNSKey = @"apns_token";
-NSString *const kFIRInstanceIDTokenOptionsAPNSIsSandboxKey = @"apns_sandbox";
-NSString *const kFIRInstanceIDTokenOptionsFirebaseAppIDKey = @"gmp_app_id";
-NSString *const kFIRInstanceIDParamInstanceID = @"appid";
-
-NSString *const kFIRInstanceIDAppDelegateProxyEnabledInfoPlistKey =
-    @"FirebaseAppDelegateProxyEnabled";
-
-// iOS Keychain error https://forums.developer.apple.com/thread/4743
-// An undocumented error code hence need to be redeclared.
-const int kFIRInstanceIDSecMissingEntitlementErrorCode = -34018;

+ 0 - 47
Firebase/InstanceID/FIRInstanceIDDefines.h

@@ -1,47 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef FIRInstanceIDLib_FIRInstanceIDDefines_h
-#define FIRInstanceIDLib_FIRInstanceIDDefines_h
-
-#define _FIRInstanceID_VERBOSE_LOGGING 1
-
-// Verbose Logging
-#if (_FIRInstanceID_VERBOSE_LOGGING)
-#define FIRInstanceID_DEV_VERBOSE_LOG(...) NSLog(__VA_ARGS__)
-#else
-#define FIRInstanceID_DEV_VERBOSE_LOG(...) \
-  do {                                     \
-  } while (0)
-#endif  // VERBOSE_LOGGING
-
-// WEAKIFY & STRONGIFY
-// Helper macro.
-#define _FIRInstanceID_WEAKNAME(VAR) VAR##_weak_
-
-#define FIRInstanceID_WEAKIFY(VAR) __weak __typeof__(VAR) _FIRInstanceID_WEAKNAME(VAR) = (VAR);
-
-#define FIRInstanceID_STRONGIFY(VAR)                                                \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\"") \
-      __strong __typeof__(VAR) VAR = _FIRInstanceID_WEAKNAME(VAR);                  \
-  _Pragma("clang diagnostic pop")
-
-// Type Conversions (used for NSInteger etc)
-#ifndef _FIRInstanceID_L
-#define _FIRInstanceID_L(v) (long)(v)
-#endif
-
-#endif

+ 0 - 62
Firebase/InstanceID/FIRInstanceIDKeychain.h

@@ -1,62 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-/* The Keychain error domain */
-extern NSString *const kFIRInstanceIDKeychainErrorDomain;
-
-/*
- * Wrapping the keychain operations in a serialize queue. This is to avoid keychain operation
- * blocking main queue.
- */
-@interface FIRInstanceIDKeychain : NSObject
-
-/**
- *  FIRInstanceIDKeychain.
- *
- *  @return A shared instance of FIRInstanceIDKeychain.
- */
-+ (instancetype)sharedInstance;
-
-/**
- *  Get keychain items matching the given a query.
- *
- *  @param keychainQuery    The keychain query.
- *
- *  @return                 An CFTypeRef result matching the provided inputs.
- */
-- (CFTypeRef)itemWithQuery:(NSDictionary *)keychainQuery;
-
-/**
- *  Remove the cached items from the keychain matching the query.
- *
- *  @param keychainQuery    The keychain query.
- *  @param handler          The callback handler which is invoked when the remove operation is
- *                          complete, with an error if there is any.
- */
-- (void)removeItemWithQuery:(NSDictionary *)keychainQuery handler:(void (^)(NSError *error))handler;
-
-/**
- *  Add the item with a given query.
- *
- *  @param keychainQuery    The keychain query.
- *  @param handler          The callback handler which is invoked when the add operation is
- *                          complete, with an error if there is any.
- */
-- (void)addItemWithQuery:(NSDictionary *)keychainQuery handler:(void (^)(NSError *))handler;
-
-@end

+ 0 - 114
Firebase/InstanceID/FIRInstanceIDKeychain.m

@@ -1,114 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDKeychain.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-
-NSString *const kFIRInstanceIDKeychainErrorDomain = @"com.google.iid";
-
-@interface FIRInstanceIDKeychain () {
-  dispatch_queue_t _keychainOperationQueue;
-}
-
-@end
-
-@implementation FIRInstanceIDKeychain
-
-+ (instancetype)sharedInstance {
-  static FIRInstanceIDKeychain *sharedInstance;
-  static dispatch_once_t onceToken;
-  dispatch_once(&onceToken, ^{
-    sharedInstance = [[FIRInstanceIDKeychain alloc] init];
-  });
-  return sharedInstance;
-}
-
-- (instancetype)init {
-  self = [super init];
-  if (self) {
-    _keychainOperationQueue =
-        dispatch_queue_create("com.google.FirebaseInstanceID.Keychain", DISPATCH_QUEUE_SERIAL);
-  }
-  return self;
-}
-
-- (CFTypeRef)itemWithQuery:(NSDictionary *)keychainQuery {
-  __block SecKeyRef keyRef = NULL;
-  dispatch_sync(_keychainOperationQueue, ^{
-    OSStatus status =
-        SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyRef);
-
-    if (status != noErr) {
-      if (keyRef) {
-        CFRelease(keyRef);
-      }
-      FIRInstanceIDLoggerDebug(kFIRInstanceIDKeychainReadItemError,
-                               @"Info is not found in Keychain. OSStatus: %d. Keychain query: %@",
-                               (int)status, keychainQuery);
-    }
-  });
-  return keyRef;
-}
-
-- (void)removeItemWithQuery:(NSDictionary *)keychainQuery
-                    handler:(void (^)(NSError *error))handler {
-  dispatch_async(_keychainOperationQueue, ^{
-    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
-    if (status != noErr) {
-      FIRInstanceIDLoggerDebug(
-          kFIRInstanceIDKeychainDeleteItemError,
-          @"Couldn't delete item from Keychain OSStatus: %d with the keychain query %@",
-          (int)status, keychainQuery);
-    }
-
-    if (handler) {
-      NSError *error;
-      // When item is not found, it should NOT be considered as an error. The operation should
-      // continue.
-      if (status != noErr && status != errSecItemNotFound) {
-        error = [NSError errorWithDomain:kFIRInstanceIDKeychainErrorDomain
-                                    code:status
-                                userInfo:nil];
-      }
-      dispatch_async(dispatch_get_main_queue(), ^{
-        handler(error);
-      });
-    }
-  });
-}
-
-- (void)addItemWithQuery:(NSDictionary *)keychainQuery handler:(void (^)(NSError *))handler {
-  dispatch_async(_keychainOperationQueue, ^{
-    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
-
-    if (handler) {
-      NSError *error;
-      if (status != noErr) {
-        FIRInstanceIDLoggerWarning(kFIRInstanceIDKeychainAddItemError,
-                                   @"Couldn't add item to Keychain OSStatus: %d", (int)status);
-        error = [NSError errorWithDomain:kFIRInstanceIDKeychainErrorDomain
-                                    code:status
-                                userInfo:nil];
-      }
-      dispatch_async(dispatch_get_main_queue(), ^{
-        handler(error);
-      });
-    }
-  });
-}
-
-@end

+ 0 - 66
Firebase/InstanceID/FIRInstanceIDLogger.h

@@ -1,66 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRIMessageCode.h"
-
-// The convenience macros are only defined if they haven't already been defined.
-#ifndef FIRInstanceIDLoggerInfo
-
-// Convenience macros that log to the shared GTMLogger instance. These macros
-// are how users should typically log to FIRInstanceIDLogger.
-#define FIRInstanceIDLoggerDebug(code, ...) \
-  [FIRInstanceIDSharedLogger() logFuncDebug:__func__ messageCode:code msg:__VA_ARGS__]
-#define FIRInstanceIDLoggerInfo(code, ...) \
-  [FIRInstanceIDSharedLogger() logFuncInfo:__func__ messageCode:code msg:__VA_ARGS__]
-#define FIRInstanceIDLoggerNotice(code, ...) \
-  [FIRInstanceIDSharedLogger() logFuncNotice:__func__ messageCode:code msg:__VA_ARGS__]
-#define FIRInstanceIDLoggerWarning(code, ...) \
-  [FIRInstanceIDSharedLogger() logFuncWarning:__func__ messageCode:code msg:__VA_ARGS__]
-#define FIRInstanceIDLoggerError(code, ...) \
-  [FIRInstanceIDSharedLogger() logFuncError:__func__ messageCode:code msg:__VA_ARGS__]
-
-#endif  // !defined(FIRInstanceIDLoggerInfo)
-
-@interface FIRInstanceIDLogger : NSObject
-
-- (void)logFuncDebug:(const char *)func
-         messageCode:(FIRInstanceIDMessageCode)messageCode
-                 msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4);
-
-- (void)logFuncInfo:(const char *)func
-        messageCode:(FIRInstanceIDMessageCode)messageCode
-                msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4);
-
-- (void)logFuncNotice:(const char *)func
-          messageCode:(FIRInstanceIDMessageCode)messageCode
-                  msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4);
-
-- (void)logFuncWarning:(const char *)func
-           messageCode:(FIRInstanceIDMessageCode)messageCode
-                   msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4);
-
-- (void)logFuncError:(const char *)func
-         messageCode:(FIRInstanceIDMessageCode)messageCode
-                 msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4);
-
-@end
-
-/**
- * Instantiates and/or returns a shared GTMLogger used exclusively
- * for InstanceID log messages.
- * @return the shared GTMLogger instance
- */
-FIRInstanceIDLogger *FIRInstanceIDSharedLogger(void);

+ 0 - 92
Firebase/InstanceID/FIRInstanceIDLogger.m

@@ -1,92 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-
-// Re-definition of FIRLogger service, as it is not included in :FIRAppHeaders target
-NSString *const kFIRInstanceIDLoggerService = @"[Firebase/InstanceID]";
-
-@implementation FIRInstanceIDLogger
-
-#pragma mark - Log Helpers
-
-+ (NSString *)formatMessageCode:(FIRInstanceIDMessageCode)messageCode {
-  return [NSString stringWithFormat:@"I-IID%06ld", (long)messageCode];
-}
-
-- (void)logFuncDebug:(const char *)func
-         messageCode:(FIRInstanceIDMessageCode)messageCode
-                 msg:(NSString *)fmt, ... {
-  va_list args;
-  va_start(args, fmt);
-  FIRLogBasic(FIRLoggerLevelDebug, kFIRInstanceIDLoggerService,
-              [FIRInstanceIDLogger formatMessageCode:messageCode], fmt, args);
-  va_end(args);
-}
-
-- (void)logFuncInfo:(const char *)func
-        messageCode:(FIRInstanceIDMessageCode)messageCode
-                msg:(NSString *)fmt, ... {
-  va_list args;
-  va_start(args, fmt);
-  FIRLogBasic(FIRLoggerLevelInfo, kFIRInstanceIDLoggerService,
-              [FIRInstanceIDLogger formatMessageCode:messageCode], fmt, args);
-  va_end(args);
-}
-
-- (void)logFuncNotice:(const char *)func
-          messageCode:(FIRInstanceIDMessageCode)messageCode
-                  msg:(NSString *)fmt, ... {
-  va_list args;
-  va_start(args, fmt);
-  FIRLogBasic(FIRLoggerLevelNotice, kFIRInstanceIDLoggerService,
-              [FIRInstanceIDLogger formatMessageCode:messageCode], fmt, args);
-  va_end(args);
-}
-
-- (void)logFuncWarning:(const char *)func
-           messageCode:(FIRInstanceIDMessageCode)messageCode
-                   msg:(NSString *)fmt, ... {
-  va_list args;
-  va_start(args, fmt);
-  FIRLogBasic(FIRLoggerLevelWarning, kFIRInstanceIDLoggerService,
-              [FIRInstanceIDLogger formatMessageCode:messageCode], fmt, args);
-  va_end(args);
-}
-
-- (void)logFuncError:(const char *)func
-         messageCode:(FIRInstanceIDMessageCode)messageCode
-                 msg:(NSString *)fmt, ... {
-  va_list args;
-  va_start(args, fmt);
-  FIRLogBasic(FIRLoggerLevelError, kFIRInstanceIDLoggerService,
-              [FIRInstanceIDLogger formatMessageCode:messageCode], fmt, args);
-  va_end(args);
-}
-
-@end
-
-FIRInstanceIDLogger *FIRInstanceIDSharedLogger() {
-  static dispatch_once_t onceToken;
-  static FIRInstanceIDLogger *logger;
-  dispatch_once(&onceToken, ^{
-    logger = [[FIRInstanceIDLogger alloc] init];
-  });
-
-  return logger;
-}

+ 0 - 188
Firebase/InstanceID/FIRInstanceIDStore.h

@@ -1,188 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-NS_ASSUME_NONNULL_BEGIN
-
-@class FIRInstanceIDBackupExcludedPlist;
-@class FIRInstanceIDCheckinPreferences;
-@class FIRInstanceIDCheckinStore;
-@class FIRInstanceIDTokenInfo;
-@class FIRInstanceIDTokenStore;
-
-@class FIRInstanceIDStore;
-@protocol FIRInstanceIDStoreDelegate <NSObject>
-
-/**
- *  This is called when the store has decided to invalide its tokens associated with the
- *  previous checkin credentials. After deleting the tokens locally, it calls this method
- *  to notify the delegate of the change. If possible, the delegate should use this time
- *  to request the invalidation of the tokens on the server as well.
- */
-- (void)store:(FIRInstanceIDStore *)store
-    didDeleteFCMScopedTokensForCheckin:(FIRInstanceIDCheckinPreferences *)checkin;
-
-@end
-
-/**
- *  Used to persist the InstanceID tokens. This is also used to cache the Checkin
- *  credentials.  The store also checks for stale entries in the store and
- *  let's us know if things in the store are stale or not. It does not however
- *  acts on stale entries in anyway.
- */
-@interface FIRInstanceIDStore : NSObject
-
-/**
- *  The delegate set in the initializer which is notified of changes in the store.
- */
-@property(nonatomic, readonly, weak) NSObject<FIRInstanceIDStoreDelegate> *delegate;
-
-- (instancetype)init __attribute__((unavailable("Use initWithDelegate: instead.")));
-
-/**
- *  Initialize a default store to persist InstanceID tokens and options.
- *
- *  @param delegate The delegate with which to be notified of changes in the store.
- *  @return Store to persist InstanceID tokens.
- */
-- (instancetype)initWithDelegate:(NSObject<FIRInstanceIDStoreDelegate> *)delegate;
-
-/**
- *  Initialize a store with the token store used to persist tokens, and a checkin store.
- *  Used for testing.
- *
- *  @param checkinStore Persistent store that persists checkin preferences.
- *  @param tokenStore Persistent store that persists tokens.
- *
- *  @return Store to persist InstanceID tokens and options.
- */
-- (instancetype)initWithCheckinStore:(FIRInstanceIDCheckinStore *)checkinStore
-                          tokenStore:(FIRInstanceIDTokenStore *)tokenStore
-                            delegate:(NSObject<FIRInstanceIDStoreDelegate> *)delegate
-    NS_DESIGNATED_INITIALIZER;
-
-#pragma mark - Save
-/**
- *  Save the instanceID token info to the store.
- *
- *  @param tokenInfo     The token info to store.
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- */
-- (void)saveTokenInfo:(FIRInstanceIDTokenInfo *)tokenInfo handler:(void (^)(NSError *))handler;
-
-/*
- * Save instanceID token info to cache only.
- */
-- (void)saveTokenInfoInCacheOnly:(FIRInstanceIDTokenInfo *)tokenInfo;
-
-#pragma mark - Get
-
-/**
- *  Get the cached token info.
- *
- *  @param authorizedEntity The authorized entity for which we want the token.
- *  @param scope            The scope for which we want the token.
- *
- *  @return The cached token info if any for the given authorizedEntity and scope else
- *          returns nil.
- */
-- (nullable FIRInstanceIDTokenInfo *)tokenInfoWithAuthorizedEntity:(NSString *)authorizedEntity
-                                                             scope:(NSString *)scope;
-/**
- *  Return all cached token infos from the Keychain.
- *
- *  @return The cached token infos, if any, that are stored in the Keychain.
- */
-- (NSArray<FIRInstanceIDTokenInfo *> *)cachedTokenInfos;
-
-#pragma mark - Delete
-
-/**
- *  Remove the cached token for a given authorizedEntity and scope. If the token was never
- *  cached or deleted from the cache before this is a no-op.
- *
- *  @param authorizedEntity The authorizedEntity for the cached token.
- *  @param scope            The scope for the cached token
- */
-- (void)removeCachedTokenWithAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope;
-
-/**
- *  Removes all cached tokens from the persistent store. In case deleting the cached tokens
- *  fails we try to delete the backup excluded plist that stores the tokens.
- *
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- *
- */
-- (void)removeAllCachedTokensWithHandler:(nullable void (^)(NSError *error))handler;
-
-#pragma mark - Persisting Checkin Preferences
-
-/**
- *  Save the checkin preferences
- *
- *  @param preferences   Checkin preferences to save.
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- */
-- (void)saveCheckinPreferences:(FIRInstanceIDCheckinPreferences *)preferences
-                       handler:(nullable void (^)(NSError *error))handler;
-
-/**
- *  Return the cached checkin preferences.
- *
- *  @return Checkin preferences.
- */
-- (FIRInstanceIDCheckinPreferences *)cachedCheckinPreferences;
-
-/**
- *  Remove the cached checkin preferences from the store.
- *
- *  @param handler       The callback handler which is invoked when the operation is complete,
- *                       with an error if there is any.
- */
-- (void)removeCheckinPreferencesWithHandler:(nullable void (^)(NSError *error))handler;
-
-#pragma mark - Standard Directory sub-directory
-
-/**
- *  Check if supported directory has InstanceID subdirectory
- *
- *  @return YES if the Application Support directory has InstanceID subdirectory else NO.
- */
-+ (BOOL)hasSubDirectory:(NSString *)subDirectoryName;
-
-/**
- *  Create InstanceID subdirectory in Application support directory.
- *
- *  @return YES if the subdirectory was created successfully else NO.
- */
-+ (BOOL)createSubDirectory:(NSString *)subDirectoryName;
-
-/**
- *  Removes Application Support subdirectory for InstanceID.
- *
- *  @param error The error object if any while trying to delete the sub-directory.
- *
- *  @return YES if the deletion was successful else NO.
- */
-+ (BOOL)removeSubDirectory:(NSString *)subDirectoryName error:(NSError **)error;
-
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 243
Firebase/InstanceID/FIRInstanceIDStore.m

@@ -1,243 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDStore.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDCheckinStore.h"
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenStore.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-// NOTE: These values should be in sync with what InstanceID saves in as.
-static NSString *const kCheckinFileName = @"g-checkin";
-
-// APNS token (use the old key value i.e. with prefix GMS)
-static NSString *const kFIRInstanceIDLibraryVersion = @"GMSInstanceID-version";
-
-@interface FIRInstanceIDStore ()
-
-@property(nonatomic, readwrite, strong) FIRInstanceIDCheckinStore *checkinStore;
-@property(nonatomic, readwrite, strong) FIRInstanceIDTokenStore *tokenStore;
-
-@end
-
-@implementation FIRInstanceIDStore
-
-- (instancetype)initWithDelegate:(NSObject<FIRInstanceIDStoreDelegate> *)delegate {
-  FIRInstanceIDCheckinStore *checkinStore = [[FIRInstanceIDCheckinStore alloc]
-      initWithCheckinPlistFileName:kCheckinFileName
-                  subDirectoryName:kFIRInstanceIDSubDirectoryName];
-
-  FIRInstanceIDTokenStore *tokenStore = [FIRInstanceIDTokenStore defaultStore];
-
-  return [self initWithCheckinStore:checkinStore tokenStore:tokenStore delegate:delegate];
-}
-
-- (instancetype)initWithCheckinStore:(FIRInstanceIDCheckinStore *)checkinStore
-                          tokenStore:(FIRInstanceIDTokenStore *)tokenStore
-                            delegate:(NSObject<FIRInstanceIDStoreDelegate> *)delegate {
-  self = [super init];
-  if (self) {
-    _checkinStore = checkinStore;
-    _tokenStore = tokenStore;
-    _delegate = delegate;
-    [self resetCredentialsIfNeeded];
-  }
-  return self;
-}
-
-#pragma mark - Upgrades
-
-+ (BOOL)hasSubDirectory:(NSString *)subDirectoryName {
-  NSString *subDirectoryPath = [self pathForSupportSubDirectory:subDirectoryName];
-  BOOL isDirectory;
-  if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
-                                            isDirectory:&isDirectory]) {
-    return NO;
-  } else if (!isDirectory) {
-    return NO;
-  }
-  return YES;
-}
-
-+ (NSSearchPathDirectory)supportedDirectory {
-#if TARGET_OS_TV
-  return NSCachesDirectory;
-#else
-  return NSApplicationSupportDirectory;
-#endif
-}
-
-+ (NSString *)pathForSupportSubDirectory:(NSString *)subDirectoryName {
-  NSArray *directoryPaths =
-      NSSearchPathForDirectoriesInDomains([self supportedDirectory], NSUserDomainMask, YES);
-  NSString *dirPath = directoryPaths.lastObject;
-  NSArray *components = @[ dirPath, subDirectoryName ];
-  return [NSString pathWithComponents:components];
-}
-
-+ (BOOL)createSubDirectory:(NSString *)subDirectoryName {
-  NSString *subDirectoryPath = [self pathForSupportSubDirectory:subDirectoryName];
-  BOOL hasSubDirectory;
-
-  if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
-                                            isDirectory:&hasSubDirectory]) {
-    NSError *error;
-    [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
-                              withIntermediateDirectories:YES
-                                               attributes:nil
-                                                    error:&error];
-    if (error) {
-      FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeStore000,
-                               @"Cannot create directory %@, error: %@", subDirectoryPath, error);
-      return NO;
-    }
-  } else {
-    if (!hasSubDirectory) {
-      FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeStore001,
-                               @"Found file instead of directory at %@", subDirectoryPath);
-      return NO;
-    }
-  }
-  return YES;
-}
-
-+ (BOOL)removeSubDirectory:(NSString *)subDirectoryName error:(NSError **)error {
-  if ([self hasSubDirectory:subDirectoryName]) {
-    NSString *subDirectoryPath = [self pathForSupportSubDirectory:subDirectoryName];
-    BOOL isDirectory;
-    if ([[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
-                                             isDirectory:&isDirectory]) {
-      return [[NSFileManager defaultManager] removeItemAtPath:subDirectoryPath error:error];
-    }
-  }
-  return YES;
-}
-
-/**
- *  Reset the keychain preferences if the app had been deleted earlier and then reinstalled.
- *  Keychain preferences are not cleared in the above scenario so explicitly clear them.
- *
- *  In case of an iCloud backup and restore the Keychain preferences should already be empty
- *  since the Keychain items are marked with `*BackupThisDeviceOnly`.
- */
-- (void)resetCredentialsIfNeeded {
-  BOOL checkinPlistExists = [self.checkinStore hasCheckinPlist];
-  // Checkin info existed in backup excluded plist. Should not be a fresh install.
-  if (checkinPlistExists) {
-    return;
-  }
-
-  // Resets checkin in keychain if a fresh install.
-  // Keychain can still exist even if app is uninstalled.
-  FIRInstanceIDCheckinPreferences *oldCheckinPreferences =
-      [self.checkinStore cachedCheckinPreferences];
-
-  if (oldCheckinPreferences) {
-    [self.checkinStore removeCheckinPreferencesWithHandler:^(NSError *error) {
-      if (!error) {
-        FIRInstanceIDLoggerDebug(
-            kFIRInstanceIDMessageCodeStore002,
-            @"Removed cached checkin preferences from Keychain because this is a fresh install.");
-      } else {
-        FIRInstanceIDLoggerError(
-            kFIRInstanceIDMessageCodeStore003,
-            @"Couldn't remove cached checkin preferences for a fresh install. Error: %@", error);
-      }
-      if (oldCheckinPreferences.deviceID.length && oldCheckinPreferences.secretToken.length) {
-        FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeStore006,
-                                 @"App reset detected. Will delete server registrations.");
-        // We don't really need to delete old FCM tokens created via IID auth tokens since
-        // those tokens are already hashed by APNS token as the has so creating a new
-        // token should automatically delete the old-token.
-        [self.delegate store:self didDeleteFCMScopedTokensForCheckin:oldCheckinPreferences];
-      } else {
-        FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeStore009,
-                                 @"App reset detected but no valid checkin auth preferences found."
-                                 @" Will not delete server registrations.");
-      }
-    }];
-  }
-}
-
-#pragma mark - Get
-
-- (FIRInstanceIDTokenInfo *)tokenInfoWithAuthorizedEntity:(NSString *)authorizedEntity
-                                                    scope:(NSString *)scope {
-  // TODO(chliangGoogle): If we don't have the token plist we should delete all the tokens from
-  // the keychain. This is because not having the plist signifies a backup and restore operation.
-  // In case the keychain has any tokens these would now be stale and therefore should be
-  // deleted.
-  if (![authorizedEntity length] || ![scope length]) {
-    return nil;
-  }
-  FIRInstanceIDTokenInfo *info = [self.tokenStore tokenInfoWithAuthorizedEntity:authorizedEntity
-                                                                          scope:scope];
-  return info;
-}
-
-- (NSArray<FIRInstanceIDTokenInfo *> *)cachedTokenInfos {
-  return [self.tokenStore cachedTokenInfos];
-}
-
-#pragma mark - Save
-
-- (void)saveTokenInfo:(FIRInstanceIDTokenInfo *)tokenInfo
-              handler:(void (^)(NSError *error))handler {
-  [self.tokenStore saveTokenInfo:tokenInfo handler:handler];
-}
-
-- (void)saveTokenInfoInCacheOnly:(FIRInstanceIDTokenInfo *)tokenInfo {
-  [self.tokenStore saveTokenInfoInCacheOnly:tokenInfo];
-}
-
-#pragma mark - Delete
-
-- (void)removeCachedTokenWithAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope {
-  if (![authorizedEntity length] || ![scope length]) {
-    FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeStore012,
-                             @"Will not delete token with invalid entity: %@, scope: %@",
-                             authorizedEntity, scope);
-    return;
-  }
-  [self.tokenStore removeTokenWithAuthorizedEntity:authorizedEntity scope:scope];
-}
-
-- (void)removeAllCachedTokensWithHandler:(void (^)(NSError *error))handler {
-  [self.tokenStore removeAllTokensWithHandler:handler];
-}
-
-#pragma mark - FIRInstanceIDCheckinCache protocol
-
-- (void)saveCheckinPreferences:(FIRInstanceIDCheckinPreferences *)preferences
-                       handler:(void (^)(NSError *error))handler {
-  [self.checkinStore saveCheckinPreferences:preferences handler:handler];
-}
-
-- (FIRInstanceIDCheckinPreferences *)cachedCheckinPreferences {
-  return [self.checkinStore cachedCheckinPreferences];
-}
-
-- (void)removeCheckinPreferencesWithHandler:(void (^)(NSError *))handler {
-  [self.checkinStore removeCheckinPreferencesWithHandler:^(NSError *error) {
-    if (handler) {
-      handler(error);
-    }
-  }];
-}
-
-@end

+ 0 - 31
Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.h

@@ -1,31 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation.h"
-
-NS_ASSUME_NONNULL_BEGIN
-
-@interface FIRInstanceIDTokenDeleteOperation : FIRInstanceIDTokenOperation
-
-- (instancetype)initWithAuthorizedEntity:(nullable NSString *)authorizedEntity
-                                   scope:(nullable NSString *)scope
-                      checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
-                              instanceID:(nullable NSString *)instanceID
-                                  action:(FIRInstanceIDTokenAction)action;
-
-@end
-
-NS_ASSUME_NONNULL_END

+ 0 - 119
Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.m

@@ -1,119 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenDeleteOperation.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDDefines.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation+Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-@implementation FIRInstanceIDTokenDeleteOperation
-
-- (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
-                                   scope:(NSString *)scope
-                      checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
-                              instanceID:(NSString *)instanceID
-                                  action:(FIRInstanceIDTokenAction)action {
-  self = [super initWithAction:action
-           forAuthorizedEntity:authorizedEntity
-                         scope:scope
-                       options:nil
-            checkinPreferences:checkinPreferences
-                    instanceID:instanceID];
-  if (self) {
-  }
-  return self;
-}
-
-- (void)performTokenOperation {
-  NSMutableURLRequest *request = [self tokenRequest];
-
-  // Build form-encoded body
-  NSString *deviceAuthID = self.checkinPreferences.deviceID;
-  NSMutableArray<NSURLQueryItem *> *queryItems =
-      [FIRInstanceIDTokenOperation standardQueryItemsWithDeviceID:deviceAuthID scope:self.scope];
-  [queryItems addObject:[NSURLQueryItem queryItemWithName:@"delete" value:@"true"]];
-  if (self.action == FIRInstanceIDTokenActionDeleteTokenAndIID) {
-    [queryItems addObject:[NSURLQueryItem queryItemWithName:@"iid-operation" value:@"delete"]];
-  }
-  if (self.authorizedEntity) {
-    [queryItems addObject:[NSURLQueryItem queryItemWithName:@"sender" value:self.authorizedEntity]];
-  }
-  // Typically we include our public key-signed url items, but in some cases (like deleting all FCM
-  // tokens), we don't.
-  if (self.instanceID.length > 0) {
-    [queryItems addObject:[NSURLQueryItem queryItemWithName:kFIRInstanceIDParamInstanceID
-                                                      value:self.instanceID]];
-  }
-
-  NSURLComponents *components = [[NSURLComponents alloc] init];
-  components.queryItems = queryItems;
-  NSString *content = components.query;
-  request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenDeleteOperationFetchRequest,
-                           @"Unregister request to %@ content: %@", FIRInstanceIDRegisterServer(),
-                           content);
-
-  FIRInstanceID_WEAKIFY(self);
-  void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
-      ^(NSData *data, NSURLResponse *response, NSError *error) {
-        FIRInstanceID_STRONGIFY(self);
-        [self handleResponseWithData:data response:response error:error];
-      };
-
-  // Test block
-  if (self.testBlock) {
-    self.testBlock(request, requestHandler);
-    return;
-  }
-
-  NSURLSession *session = [FIRInstanceIDTokenOperation sharedURLSession];
-  self.dataTask = [session dataTaskWithRequest:request completionHandler:requestHandler];
-  [self.dataTask resume];
-}
-
-- (void)handleResponseWithData:(NSData *)data
-                      response:(NSURLResponse *)response
-                         error:(NSError *)error {
-  if (error) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenDeleteOperationRequestError,
-                             @"Device unregister HTTP fetch error. Error code: %ld",
-                             _FIRInstanceID_L(error.code));
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
-    return;
-  }
-
-  NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
-  if (dataResponse.length == 0) {
-    NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
-    return;
-  }
-
-  if (![dataResponse hasPrefix:@"deleted="] && ![dataResponse hasPrefix:@"token="]) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenDeleteOperationBadResponse,
-                             @"Invalid unregister response %@", response);
-    NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
-    return;
-  }
-  [self finishWithResult:FIRInstanceIDTokenOperationSucceeded token:nil error:nil];
-}
-@end

+ 0 - 34
Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.h

@@ -1,34 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation.h"
-
-NS_ASSUME_NONNULL_BEGIN
-
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDFirebaseUserAgentKey;
-
-FOUNDATION_EXPORT NSString *const kFIRInstanceIDFirebaseHeartbeatKey;
-
-@interface FIRInstanceIDTokenFetchOperation : FIRInstanceIDTokenOperation
-
-- (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
-                                   scope:(NSString *)scope
-                                 options:(nullable NSDictionary<NSString *, NSString *> *)options
-                      checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
-                              instanceID:(NSString *)instanceID;
-
-@end
-NS_ASSUME_NONNULL_END

+ 0 - 207
Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.m

@@ -1,207 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import "Firebase/InstanceID/FIRInstanceIDTokenFetchOperation.h"
-
-#import "Firebase/InstanceID/FIRInstanceIDConstants.h"
-#import "Firebase/InstanceID/FIRInstanceIDDefines.h"
-#import "Firebase/InstanceID/FIRInstanceIDLogger.h"
-#import "Firebase/InstanceID/FIRInstanceIDTokenOperation+Private.h"
-#import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
-#import "Firebase/InstanceID/NSError+FIRInstanceID.h"
-#import "Firebase/InstanceID/Private/FIRInstanceIDCheckinPreferences.h"
-
-#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
-
-// We can have a static int since this error should theoretically only
-// happen once (for the first time). If it repeats there is something
-// else that is wrong.
-static int phoneRegistrationErrorRetryCount = 0;
-static const int kMaxPhoneRegistrationErrorRetryCount = 10;
-NSString *const kFIRInstanceIDFirebaseUserAgentKey = @"X-firebase-client";
-NSString *const kFIRInstanceIDFirebaseHeartbeatKey = @"X-firebase-client-log-type";
-NSString *const kFIRInstanceIDHeartbeatTag = @"fire-iid";
-
-@implementation FIRInstanceIDTokenFetchOperation
-
-- (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
-                                   scope:(NSString *)scope
-                                 options:(nullable NSDictionary<NSString *, NSString *> *)options
-                      checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
-                              instanceID:(NSString *)instanceID {
-  self = [super initWithAction:FIRInstanceIDTokenActionFetch
-           forAuthorizedEntity:authorizedEntity
-                         scope:scope
-                       options:options
-            checkinPreferences:checkinPreferences
-                    instanceID:instanceID];
-  if (self) {
-  }
-  return self;
-}
-
-- (void)performTokenOperation {
-  NSMutableURLRequest *request = [self tokenRequest];
-  NSString *checkinVersionInfo = self.checkinPreferences.versionInfo;
-  [request setValue:checkinVersionInfo forHTTPHeaderField:@"info"];
-  [request setValue:[FIRApp firebaseUserAgent]
-      forHTTPHeaderField:kFIRInstanceIDFirebaseUserAgentKey];
-  [request setValue:@([FIRHeartbeatInfo heartbeatCodeForTag:kFIRInstanceIDHeartbeatTag]).stringValue
-      forHTTPHeaderField:kFIRInstanceIDFirebaseHeartbeatKey];
-
-  // Build form-encoded body
-  NSString *deviceAuthID = self.checkinPreferences.deviceID;
-  NSMutableArray<NSURLQueryItem *> *queryItems =
-      [[self class] standardQueryItemsWithDeviceID:deviceAuthID scope:self.scope];
-  [queryItems addObject:[NSURLQueryItem queryItemWithName:@"sender" value:self.authorizedEntity]];
-  [queryItems addObject:[NSURLQueryItem queryItemWithName:@"X-subtype"
-                                                    value:self.authorizedEntity]];
-
-  if (self.instanceID.length > 0) {
-    [queryItems addObject:[NSURLQueryItem queryItemWithName:kFIRInstanceIDParamInstanceID
-                                                      value:self.instanceID]];
-  }
-  // Create query items from passed-in options
-  id apnsTokenData = self.options[kFIRInstanceIDTokenOptionsAPNSKey];
-  id apnsSandboxValue = self.options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey];
-  if ([apnsTokenData isKindOfClass:[NSData class]] &&
-      [apnsSandboxValue isKindOfClass:[NSNumber class]]) {
-    NSString *APNSString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
-        apnsTokenData, ((NSNumber *)apnsSandboxValue).boolValue);
-    // The name of the query item happens to be the same as the dictionary key
-    NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:kFIRInstanceIDTokenOptionsAPNSKey
-                                                       value:APNSString];
-    [queryItems addObject:item];
-  }
-  id firebaseAppID = self.options[kFIRInstanceIDTokenOptionsFirebaseAppIDKey];
-  if ([firebaseAppID isKindOfClass:[NSString class]]) {
-    // The name of the query item happens to be the same as the dictionary key
-    NSURLQueryItem *item =
-        [NSURLQueryItem queryItemWithName:kFIRInstanceIDTokenOptionsFirebaseAppIDKey
-                                    value:(NSString *)firebaseAppID];
-    [queryItems addObject:item];
-  }
-
-  NSURLComponents *components = [[NSURLComponents alloc] init];
-  components.queryItems = queryItems;
-  NSString *content = components.query;
-  request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
-  FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationFetchRequest,
-                           @"Register request to %@ content: %@", FIRInstanceIDRegisterServer(),
-                           content);
-
-  FIRInstanceID_WEAKIFY(self);
-  void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
-      ^(NSData *data, NSURLResponse *response, NSError *error) {
-        FIRInstanceID_STRONGIFY(self);
-        [self handleResponseWithData:data response:response error:error];
-      };
-
-  // Test block
-  if (self.testBlock) {
-    self.testBlock(request, requestHandler);
-    return;
-  }
-
-  NSURLSession *session = [FIRInstanceIDTokenOperation sharedURLSession];
-  self.dataTask = [session dataTaskWithRequest:request completionHandler:requestHandler];
-  [self.dataTask resume];
-}
-
-#pragma mark - Request Handling
-
-- (void)handleResponseWithData:(NSData *)data
-                      response:(NSURLResponse *)response
-                         error:(NSError *)error {
-  if (error) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationRequestError,
-                             @"Token fetch HTTP error. Error Code: %ld", (long)error.code);
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
-    return;
-  }
-  NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
-
-  if (dataResponse.length == 0) {
-    NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
-    [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
-    return;
-  }
-  NSDictionary *parsedResponse = [self parseFetchTokenResponse:dataResponse];
-
-  if ([parsedResponse[@"token"] length]) {
-    [self finishWithResult:FIRInstanceIDTokenOperationSucceeded
-                     token:parsedResponse[@"token"]
-                     error:nil];
-    return;
-  }
-
-  NSString *errorValue = parsedResponse[@"Error"];
-  NSError *responseError;
-  if (errorValue.length) {
-    NSArray *errorComponents = [errorValue componentsSeparatedByString:@":"];
-    // HACK (Kansas replication delay), PHONE_REGISTRATION_ERROR on App
-    // uninstall and reinstall.
-    if ([errorComponents containsObject:@"PHONE_REGISTRATION_ERROR"]) {
-      // Encountered issue http://b/27043795
-      // Retry register until successful or another error encountered or a
-      // certain number of tries are over.
-
-      if (phoneRegistrationErrorRetryCount < kMaxPhoneRegistrationErrorRetryCount) {
-        const int nextRetryInterval = 1 << phoneRegistrationErrorRetryCount;
-        FIRInstanceID_WEAKIFY(self);
-
-        dispatch_after(
-            dispatch_time(DISPATCH_TIME_NOW, (int64_t)(nextRetryInterval * NSEC_PER_SEC)),
-            dispatch_get_main_queue(), ^{
-              FIRInstanceID_STRONGIFY(self);
-              phoneRegistrationErrorRetryCount++;
-              [self performTokenOperation];
-            });
-        return;
-      }
-    } else if ([errorComponents containsObject:kFIRInstanceID_CMD_RST]) {
-      // Server detected the identity we use is no longer valid.
-      NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-      [center postNotificationName:kFIRInstanceIDIdentityInvalidatedNotification object:nil];
-
-      FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal001,
-                               @"Identity is invalid. Server request identity reset.");
-      responseError =
-          [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidIdentity];
-    }
-  }
-  if (!responseError) {
-    FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationBadResponse,
-                             @"Invalid fetch response, expected 'token' or 'Error' key");
-    responseError = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
-  }
-  [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:responseError];
-}
-
-// expect a response e.g. "token=<reg id>\nGOOG.ttl=123"
-- (NSDictionary *)parseFetchTokenResponse:(NSString *)response {
-  NSArray *lines = [response componentsSeparatedByString:@"\n"];
-  NSMutableDictionary *parsedResponse = [NSMutableDictionary dictionary];
-  for (NSString *line in lines) {
-    NSArray *keyAndValue = [line componentsSeparatedByString:@"="];
-    if ([keyAndValue count] > 1) {
-      parsedResponse[keyAndValue[0]] = keyAndValue[1];
-    }
-  }
-  return parsedResponse;
-}
-
-@end

+ 0 - 92
Firebase/InstanceID/FIRInstanceIDTokenInfo.h

@@ -1,92 +0,0 @@
-/*
- * Copyright 2019 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-#import "Firebase/InstanceID/FIRInstanceIDAPNSInfo.h"
-
-NS_ASSUME_NONNULL_BEGIN
-
-/**
- *  Represents an Instance ID token, and all of the relevant information
- *  associated with it. It can read from and write to an NSDictionary object, for
- *  simple serialization.
- */
-@interface FIRInstanceIDTokenInfo : NSObject <NSCoding>
-
-/// The authorized entity (also known as Sender ID), associated with the token.
-@property(nonatomic, readonly, copy) NSString *authorizedEntity;
-/// The scope associated with the token. This is an arbitrary string, typically "*".
-@property(nonatomic, readonly, copy) NSString *scope;
-/// The token value itself, with which all other properties are associated.
-@property(nonatomic, readonly, copy) NSString *token;
-
-// These properties are nullable because they might not exist for tokens fetched from
-// legacy storage formats.
-
-/// The app version that this token represents.
-@property(nonatomic, readonly, copy, nullable) NSString *appVersion;
-/// The Firebase app ID (also known as GMP App ID), that this token is associated with.
-@property(nonatomic, readonly, copy, nullable) NSString *firebaseAppID;
-
-/// Tokens may not always be associated with an APNs token, and may be associated after
-/// being created.
-@property(nonatomic, strong, nullable) FIRInstanceIDAPNSInfo *APNSInfo;
-/// The time that this token info was updated. The cache time is writeable, since in
-/// some cases the token info may be refreshed from the server. In those situations,
-/// the cacheTime would be updated.
-@property(nonatomic, copy, nullable) NSDate *cacheTime;
-
-/**
- *  Initializes a FIRInstanceIDTokenInfo object with the required parameters. These
- *  parameters represent all the relevant associated data with a token.
- *
- *  @param authorizedEntity The authorized entity (also known as Sender ID).
- *  @param scope            The scope of the token, typically "*" meaning
- *                          it's a "default scope".
- *  @param token            The token value itself.
- *  @param appVersion       The application version that this token is associated with.
- *  @param firebaseAppID    The Firebase app ID which this token is associated with.
- *  @return An instance of FIRInstanceIDTokenInfo.
- */
-- (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
-                                   scope:(NSString *)scope
-                                   token:(NSString *)token
-                              appVersion:(nullable NSString *)appVersion
-                           firebaseAppID:(nullable NSString *)firebaseAppID;
-
-/**
- * Check whether the token is still fresh based on:
- * 1. Last fetch token is within the 7 days.
- * 2. Language setting is not changed.
- * 3. App version is current.
- * 4. GMP App ID is current.
- * 5. token is consistent with the current IID.
- * 6. APNS info has changed.
- * @param IID  The app identifiier that is used to check if token is prefixed with.
- * @return If token is fresh.
- *
- */
-- (BOOL)isFreshWithIID:(NSString *)IID;
-
-/*
- * Check whether the token is default token.
- */
-- (BOOL)isDefaultToken;
-
-@end
-
-NS_ASSUME_NONNULL_END

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません