forked from arnesson/cordova-plugin-firebase
-
-
Notifications
You must be signed in to change notification settings - Fork 469
/
AppDelegate+FirebasePlugin.m
570 lines (479 loc) · 27.2 KB
/
AppDelegate+FirebasePlugin.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#import "AppDelegate+FirebasePlugin.h"
#import "FirebasePlugin.h"
#import "FirebaseWrapper.h"
#import <objc/runtime.h>
@import UserNotifications;
@import FirebaseFirestore;
// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices running iOS 10 and above.
// Implement FIRMessagingDelegate to receive data message via FCM for devices running iOS 10 and above.
@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@end
#define kApplicationInBackgroundKey @"applicationInBackground"
@implementation AppDelegate (FirebasePlugin)
static AppDelegate* instance;
+ (AppDelegate*) instance {
return instance;
}
static NSDictionary* mutableUserInfo;
static FIRAuthStateDidChangeListenerHandle authStateChangeListener;
static bool authStateChangeListenerInitialized = false;
static FIRIDTokenDidChangeListenerHandle authIdTokenChangeListener;
static NSString* currentIdToken = @"";
static __weak id <UNUserNotificationCenterDelegate> _prevUserNotificationCenterDelegate = nil;
+ (void)load {
Method original = class_getInstanceMethod(self, @selector(application:didFinishLaunchingWithOptions:));
Method swizzled = class_getInstanceMethod(self, @selector(application:swizzledDidFinishLaunchingWithOptions:));
method_exchangeImplementations(original, swizzled);
}
- (void)setApplicationInBackground:(NSNumber *)applicationInBackground {
objc_setAssociatedObject(self, kApplicationInBackgroundKey, applicationInBackground, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSNumber *)applicationInBackground {
return objc_getAssociatedObject(self, kApplicationInBackgroundKey);
}
- (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self application:application swizzledDidFinishLaunchingWithOptions:launchOptions];
@try{
instance = self;
bool isFirebaseInitializedWithPlist = false;
if(![FIRApp defaultApp]) {
// get GoogleService-Info.plist file path
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
// if file is successfully found, use it
if(filePath){
[FirebasePlugin.firebasePlugin _logMessage:@"GoogleService-Info.plist found, setup: [FIRApp configureWithOptions]"];
// create firebase configure options passing .plist as content
FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath];
// configure FIRApp with options
[FIRApp configureWithOptions:options];
isFirebaseInitializedWithPlist = true;
}else{
// no .plist found, try default App
[FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"];
[FIRApp configure];
}
}else{
// Firebase SDK has already been initialised:
// Assume that another call (probably from another plugin) did so with the plist
isFirebaseInitializedWithPlist = true;
}
if (self.isFCMEnabled) {
// Setting the delegate even if FCM is disabled would cause conflicts with other plugins dealing
// with push notifications (e.g. `urbanairship-cordova`).
_prevUserNotificationCenterDelegate = [UNUserNotificationCenter currentNotificationCenter].delegate;
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
// Set FCM messaging delegate
[FIRMessaging messaging].delegate = self;
} else {
// This property is persistent thus ensuring it stays in sync with FCM settings in newer versions of the app.
[[FIRMessaging messaging] setAutoInitEnabled:NO];
}
// Setup Firestore
[FirebasePlugin setFirestore:[FIRFirestore firestore]];
authStateChangeListener = [[FIRAuth auth] addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) {
@try {
if(!authStateChangeListenerInitialized){
authStateChangeListenerInitialized = true;
}else{
[FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthStateChange(%@)", (user != nil ? @"true": @"false")]];
}
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}];
authIdTokenChangeListener = [[FIRAuth auth] addIDTokenDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) {
@try {
if(![FIRAuth auth].currentUser){
[FirebasePlugin.firebasePlugin executeGlobalJavascript:@"FirebasePlugin._onAuthIdTokenChange()"];
return;
}
FIRUser* user = [FIRAuth auth].currentUser;
[user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
if(error == nil){
if([token isEqualToString:currentIdToken]) return;;
currentIdToken = token;
[user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) {
if(error == nil){
[FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthIdTokenChange({\"idToken\": \"%@\", \"providerId\": \"%@\"})", token, tokenResult.signInProvider]];
}else{
[FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthIdTokenChange({\"idToken\": \"%@\"})", token]];
}
}];
}else{
[FirebasePlugin.firebasePlugin executeGlobalJavascript:@"FirebasePlugin._onAuthIdTokenChange()"];
}
}];
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin executeGlobalJavascript:@"FirebasePlugin._onAuthIdTokenChange()"];
}
}];
self.applicationInBackground = @(YES);
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
return YES;
}
- (BOOL)isFCMEnabled {
return FirebasePlugin.firebasePlugin.isFCMEnabled;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
self.applicationInBackground = @(NO);
@try {
[FirebasePlugin.firebasePlugin _logMessage:@"Enter foreground"];
[FirebasePlugin.firebasePlugin executeGlobalJavascript:@"FirebasePlugin._applicationDidBecomeActive()"];
[FirebasePlugin.firebasePlugin sendPendingNotifications];
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
[FirebasePlugin.firebasePlugin sendPendingNotifications];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
self.applicationInBackground = @(YES);
@try {
[FirebasePlugin.firebasePlugin _logMessage:@"Enter background"];
[FirebasePlugin.firebasePlugin executeGlobalJavascript:@"FirebasePlugin._applicationDidEnterBackground()"];
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
# pragma mark - FIRMessagingDelegate
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
@try{
[FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRegistrationToken: %@", fcmToken]];
[FirebasePlugin.firebasePlugin sendToken:fcmToken];
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
if (!self.isFCMEnabled) {
return;
}
[FIRMessaging messaging].APNSToken = deviceToken;
[FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didRegisterForRemoteNotificationsWithDeviceToken: %@", deviceToken]];
[FirebasePlugin.firebasePlugin sendApnsToken:[FirebasePlugin.firebasePlugin hexadecimalStringFromData:deviceToken]];
}
//Tells the app that a remote notification arrived that indicates there is data to be fetched.
// Called when a message arrives in the foreground and remote notifications permission has been granted
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
if (!self.isFCMEnabled) {
return;
}
@try{
[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
mutableUserInfo = [userInfo mutableCopy];
NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"];
bool isContentAvailable = false;
if([aps objectForKey:@"alert"] != nil){
if([aps objectForKey:@"content-available"] != nil){
NSNumber* contentAvailable = (NSNumber*) [aps objectForKey:@"content-available"];
isContentAvailable = [contentAvailable isEqualToNumber:[NSNumber numberWithInt:1]];
}
[mutableUserInfo setValue:@"notification" forKey:@"messageType"];
NSString* tap;
if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && !isContentAvailable){
tap = @"background";
}
[mutableUserInfo setValue:tap forKey:@"tap"];
}else{
[mutableUserInfo setValue:@"data" forKey:@"messageType"];
}
[FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRemoteNotification: %@", mutableUserInfo]];
completionHandler(UIBackgroundFetchResultNewData);
if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && isContentAvailable){
[FirebasePlugin.firebasePlugin _logError:@"didReceiveRemoteNotification: omitting foreground notification as content-available:1 so system notification will be shown"];
}else{
[self processMessageForForegroundNotification:mutableUserInfo];
}
if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] || !isContentAvailable){
[FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo];
}
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
// Scans a message for keys which indicate a notification should be shown.
// If found, extracts relevant keys and uses then to display a local notification
-(void)processMessageForForegroundNotification:(NSDictionary*)messageData {
bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"];
if(!showForegroundNotification){
return;
}
NSString* title = nil;
NSString* body = nil;
NSString* sound = nil;
NSNumber* badge = nil;
// Extract APNS notification keys
NSDictionary* aps = [messageData objectForKey:@"aps"];
if([aps objectForKey:@"alert"] != nil){
NSDictionary* alert = [aps objectForKey:@"alert"];
if([alert objectForKey:@"title"] != nil){
title = [alert objectForKey:@"title"];
}
if([alert objectForKey:@"body"] != nil){
body = [alert objectForKey:@"body"];
}
if([aps objectForKey:@"sound"] != nil){
sound = [aps objectForKey:@"sound"];
}
if([aps objectForKey:@"badge"] != nil){
badge = [aps objectForKey:@"badge"];
}
}
// Extract data notification keys
if([messageData objectForKey:@"notification_title"] != nil){
title = [messageData objectForKey:@"notification_title"];
}
if([messageData objectForKey:@"notification_body"] != nil){
body = [messageData objectForKey:@"notification_body"];
}
if([messageData objectForKey:@"notification_ios_sound"] != nil){
sound = [messageData objectForKey:@"notification_ios_sound"];
}
if([messageData objectForKey:@"notification_ios_badge"] != nil){
badge = [messageData objectForKey:@"notification_ios_badge"];
}
if(title == nil || body == nil){
return;
}
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
@try{
if (settings.alertSetting == UNNotificationSettingEnabled) {
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil];
NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys:
title, @"title",
body, @"body"
, nil];
NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
alert, @"alert",
nil];
if(![sound isKindOfClass:[NSString class]] || [sound isEqualToString:@"default"]){
objNotificationContent.sound = [UNNotificationSound defaultSound];
[aps setValue:sound forKey:@"sound"];
}else if(sound != nil){
objNotificationContent.sound = [UNNotificationSound soundNamed:sound];
[aps setValue:sound forKey:@"sound"];
}
if(badge != nil){
[aps setValue:badge forKey:@"badge"];
}
NSString* messageType = @"data";
if([mutableUserInfo objectForKey:@"messageType"] != nil){
messageType = [mutableUserInfo objectForKey:@"messageType"];
}
NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:
@"true", @"notification_foreground",
messageType, @"messageType",
aps, @"aps"
, nil];
objNotificationContent.userInfo = userInfo;
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
[FirebasePlugin.firebasePlugin _logMessage:@"Local Notification succeeded"];
} else {
[FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"Local Notification failed: %@", error.description]];
}
}];
}else{
[FirebasePlugin.firebasePlugin _logError:@"processMessageForForegroundNotification: cannot show notification as permission denied"];
}
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
if (!self.isFCMEnabled) {
return;
}
[FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description]];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification
{
@try {
[FirebasePlugin.firebasePlugin sendOpenNotificationSettings];
} @catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
// Asks the delegate how to handle a notification that arrived while the app was running in the foreground
// Called when an APS notification arrives when app is in foreground
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
@try{
if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]) {
if (_prevUserNotificationCenterDelegate) {
// bubbling notification
[_prevUserNotificationCenterDelegate
userNotificationCenter:center
willPresentNotification:notification
withCompletionHandler:completionHandler
];
return;
} else {
[FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as not a supported UNNotificationTrigger"];
return;
}
}
[[FIRMessaging messaging] appDidReceiveMessage:notification.request.content.userInfo];
mutableUserInfo = [notification.request.content.userInfo mutableCopy];
NSString* messageType = [mutableUserInfo objectForKey:@"messageType"];
if(![messageType isEqualToString:@"data"]){
[mutableUserInfo setValue:@"notification" forKey:@"messageType"];
}
// Print full message.
[FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: %@", mutableUserInfo]];
NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"];
bool isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]];
if(isContentAvailable){
[FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as content-available:1 so system notification will be shown"];
return;
}
bool showForegroundNotification = [mutableUserInfo objectForKey:@"notification_foreground"];
bool hasAlert = [aps objectForKey:@"alert"] != nil;
bool hasBadge = [aps objectForKey:@"badge"] != nil;
bool hasSound = [aps objectForKey:@"sound"] != nil;
if(showForegroundNotification){
[FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: foreground notification alert=%@, badge=%@, sound=%@", hasAlert ? @"YES" : @"NO", hasBadge ? @"YES" : @"NO", hasSound ? @"YES" : @"NO"]];
if(hasAlert && hasBadge && hasSound){
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound);
}else if(hasAlert && hasBadge){
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge);
}else if(hasAlert && hasSound){
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}else if(hasBadge && hasSound){
completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound);
}else if(hasAlert){
completionHandler(UNNotificationPresentationOptionAlert);
}else if(hasBadge){
completionHandler(UNNotificationPresentationOptionBadge);
}else if(hasSound){
completionHandler(UNNotificationPresentationOptionSound);
}
}else{
[FirebasePlugin.firebasePlugin _logMessage:@"willPresentNotification: foreground notification not set"];
}
if(![messageType isEqualToString:@"data"]){
[FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo];
}
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
// Asks the delegate to process the user's response to a delivered notification.
// Called when user taps on system notification
- (void) userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
@try{
if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]) {
if (_prevUserNotificationCenterDelegate) {
// bubbling event
[_prevUserNotificationCenterDelegate
userNotificationCenter:center
didReceiveNotificationResponse:response
withCompletionHandler:completionHandler
];
return;
} else {
[FirebasePlugin.firebasePlugin _logMessage:@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"];
return;
}
}
[[FIRMessaging messaging] appDidReceiveMessage:response.notification.request.content.userInfo];
mutableUserInfo = [response.notification.request.content.userInfo mutableCopy];
NSString* tap;
if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){
tap = @"background";
}else{
tap = @"foreground";
}
[mutableUserInfo setValue:tap forKey:@"tap"];
if([mutableUserInfo objectForKey:@"messageType"] == nil){
[mutableUserInfo setValue:@"notification" forKey:@"messageType"];
}
// Dynamic Actions
if (response.actionIdentifier && ![response.actionIdentifier isEqual:UNNotificationDefaultActionIdentifier]) {
[mutableUserInfo setValue:response.actionIdentifier forKey:@"action"];
}
// Print full message.
[FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"didReceiveNotificationResponse: %@", mutableUserInfo]];
[FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo];
completionHandler();
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
// Apple Sign In
- (void)authorizationController:(ASAuthorizationController *)controller
didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
@try{
CDVPluginResult* pluginResult;
NSString* errorMessage = nil;
FIROAuthCredential *credential;
if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
NSString *rawNonce = [FirebasePlugin appleSignInNonce];
if(rawNonce == nil){
errorMessage = @"Invalid state: A login callback was received, but no login request was sent.";
}else if (appleIDCredential.identityToken == nil) {
errorMessage = @"Unable to fetch identity token.";
}else{
NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken
encoding:NSUTF8StringEncoding];
if (idToken == nil) {
errorMessage = [NSString stringWithFormat:@"Unable to serialize id token from data: %@", appleIDCredential.identityToken];
}else{
// Initialize a Firebase credential.
credential = [FIROAuthProvider credentialWithProviderID:@"apple.com"
IDToken:idToken
rawNonce:rawNonce];
NSNumber* key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential];
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[result setValue:@"true" forKey:@"instantVerification"];
[result setValue:key forKey:@"id"];
[result setValue:idToken forKey:@"idToken"];
[result setValue:rawNonce forKey:@"rawNonce"];
if(appleIDCredential.fullName != nil){
if(appleIDCredential.fullName.givenName != nil){
[result setValue:appleIDCredential.fullName.givenName forKey:@"givenName"];
}
if(appleIDCredential.fullName.familyName != nil){
[result setValue:appleIDCredential.fullName.familyName forKey:@"familyName"];
}
}
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result];
}
}
if(errorMessage != nil){
[FirebasePlugin.firebasePlugin _logError:errorMessage];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
}
if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) {
[[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId];
}
}
}@catch (NSException *exception) {
[FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception];
}
}
- (void)authorizationController:(ASAuthorizationController *)controller
didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
NSString* errorMessage = [NSString stringWithFormat:@"Sign in with Apple errored: %@", error];
[FirebasePlugin.firebasePlugin _logError:errorMessage];
if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
[[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId];
}
}
- (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
return self.viewController.view.window;
}
@end