segment-integrations / analytics-ios-integration-firebase

Segment's bundled integration for Firebase on iOS
MIT License
13 stars 92 forks source link

UI API called on a background thread: -[UIApplication delegate] #39

Closed bull-xu closed 2 years ago

bull-xu commented 5 years ago

In my Firebase project, I enable the Firebase/Messaging feature.

When the SEGIntegrationsManager tries to create the Firebase integration after fetching the settings (in a background thread), the updateIntegrationsWithSettings will use the same background thread to create each integration in the factories list.

Hence theSEGFirebaseIntegration initWithSettings method is called from the background thread, which the [FIRApp configure] will try to access the shared UIApplication's delegate, causing the Xcode 10 complains the error:

=================================================================
Main Thread Checker: UI API called on a background thread: -[UIApplication delegate]
PID: 18686, TID: 5429842, Thread name: (none), Queue name: io.segment.analytics, QoS: 0
Backtrace:
4  MyApp                              0x00000001045f35bc -[FIRMessagingRemoteNotificationsProxy swizzleMethodsIfPossible] + 172
5   MyApp                              0x00000001045f3144 +[FIRMessagingRemoteNotificationsProxy swizzleMethods] + 108
6   MyApp                              0x00000001045cbdf0 -[FIRMessaging configureMessaging:] + 272
7   MyApp                              0x00000001045cbca4 +[FIRMessaging configureWithApp:] + 268
8   MyApp                              0x000000010459f37c +[FIRApp sendNotificationsToSDKs:] + 800
9   MyApp                              0x000000010459d554 +[FIRApp configureWithName:options:] + 1464
10  MyApp                              0x000000010459cf7c +[FIRApp configureWithOptions:] + 192
11  MyApp                              0x000000010459ce7c +[FIRApp configure] + 712
12  MyApp                              0x0000000104c107f8 -[SEGFirebaseIntegration initWithSettings:] + 528
13  MyApp                              0x0000000104c122fc -[SEGFirebaseIntegrationFactory createWithSettings:forAnalytics:] + 140
14  Analytics                           0x00000001063de7b4 __57-[SEGIntegrationsManager updateIntegrationsWithSettings:]_block_invoke + 584
15  Analytics                           0x00000001063d527c __seg_dispatch_specific_block_invoke + 80
16  Analytics                           0x00000001063d5190 seg_dispatch_specific + 256
17  Analytics                           0x00000001063d5420 seg_dispatch_specific_sync + 116
18  Analytics                           0x00000001063de524 -[SEGIntegrationsManager updateIntegrationsWithSettings:] + 208
19  Analytics                           0x00000001063de418 -[SEGIntegrationsManager setCachedSettings:] + 380
20  Analytics                           0x00000001063def90 __41-[SEGIntegrationsManager refreshSettings]_block_invoke_3 + 140
21  Analytics                           0x00000001063d527c __seg_dispatch_specific_block_invoke + 80
22  libdispatch.dylib                   0x0000000107e4ec28 _dispatch_call_block_and_release + 32
23  libdispatch.dylib                   0x0000000107e501c0 _dispatch_client_callout + 20
24  libdispatch.dylib                   0x0000000107e582f4 _dispatch_lane_serial_drain + 708
25  libdispatch.dylib                   0x0000000107e58ff8 _dispatch_lane_invoke + 420
26  libdispatch.dylib                   0x0000000107e62bfc _dispatch_workloop_worker_thread + 1168
27  libsystem_pthread.dylib             0x000000022f064b20 _pthread_wqthread + 316
28  libsystem_pthread.dylib             0x000000022f06add4 start_wqthread + 4

I would avoid this error by modifying the SEGFirebaseIntegrationFactory's createWithSettings method like this:


- (id<SEGIntegration>)createWithSettings:(NSDictionary *)settings forAnalytics:(SEGAnalytics *)analytics
{
  __block SEGFirebaseIntegration* integration;
  dispatch_sync(dispatch_get_main_queue(), ^{
    integration = [[SEGFirebaseIntegration alloc] initWithSettings:settings];
  });
  return integration;
}

What else I can do to prevent this error without modifying this lib's source?

gpitfield commented 5 years ago

I see this problem also, when integrating Firebase DynamicLinks, as of version 2.4. As far as I can tell, it renders the integration unusable in any app that wants to use DynamicLinks. The fix above does appear to work, although I haven't verified whether there are other side effects.

lawicko commented 5 years ago

@gpitfield I have discovered some side effects of my fix, so for you and others who want to use it, please note that the dynamic links will not work if starting the app from the cold state. This is because the fix delays the Firebase setup (namely the moment when [FIRApp configure] is called). So when starting from cold, returning true from ...didFinishLaunchingWithOptions the ...application: UIApplication, continue userActivity: NSUserActivity, restorationHandler... will be called, but at this time the Firebase SDK is not configured properly, so DynamicLinks.dynamicLinks().handleUniversalLink(url) will return false and your callback will never be called.

I have patched this for myself by posting a notification from line 22 of SEGFirebaseIntegration but this is more a hack than anything else. The proper fix should be to actually run the integration setup code on the main queue for the integrations that need this.

bull-xu commented 5 years ago

I also use the swizzling for fixing this issue:

Call FirebaseApp.exchange() before the SegmentAnalytics(apiKey: apiKey, factories: factories) then the FirebaseApp.configure() will be called in the main thread.

extension FirebaseApp {
    class func exchange() {
        let origin = #selector(configure as () -> Void)
        let with = #selector(myConfigure)
        exchangeMethod(origin, with: with)
    }

    @objc
    class func myConfigure() {
        DispatchQueue.main.async {
            myConfigure()
        }
    }

  class func exchangeMethod(_ originalSelector: Selector, with overriddenSelector: Selector) {
    guard
      let originalMethod = class_getClassMethod(self, originalSelector),
      let overriddenMethod = class_getClassMethod(self, overriddenSelector) else {
        return
    }
    method_exchangeImplementations(originalMethod, overriddenMethod)
  }
}
bull-xu commented 5 years ago

Another thing to be considered: Because the Segment will have a remote call to fetch the configuration setting options before the FirebaseApp.configure() got called. Before that, the FirebaseApp.app() is always nil, if you want to use any feature of it, you need to wait for the remote call return and configure being called. There is a notification we can use to detect this: FIRAppReadyToConfigureSDKNotification.

taraspasichnyk commented 4 years ago

@briemcnally, maybe you could add some input on this issue?