简体   繁体   中英

Firebase Google Cloud messaging from device to device

I couldn't understand how can i send message from iOS device to another iOS device, and trying to understand the difference between Firebase Notifications and Google Cloud Messaging.

Firebase Notifications say's from the server you can send a message to devices.

Google Cloud Messaging: it sends messages from server to devices(downstream) or device to server(upstream) !!

Example of upstream:

[[FIRMessaging message]sendMessage:(nonnull NSDictionary *)message
                                to:(nonnull NSString *)receiver
                     withMessageID:(nonnull NSString *)messageID
                        timeToLive:(int64_t)ttl;

What about if i need to send a push message from device to device ! Does it means after the device sends a messages to server, i have to program the firebase server to send push to client ? its really confusing !

No you cannot do this on iOS using firebase, what you should do is call a service on your firebase which will send a notification to the other device. APNS and GCM are a little different in terms of the server setup.

For GCM you just need the API key to be added in the POST call you make to https://android.googleapis.com/gcm/send which can be done anywhere server, mobile device, etc. All you need is the target devices device token and the API key.

APNS works differently you need attach the server SSL cert that you create on the Apple developer portal to authenticate yourself and send a push notification to a device. I am not sure how you could achieve this on an iOS device.

This thread clarifies the real difference between GCM and Firebase,

Real-time Push notifications with Firebase

https://firebase.google.com/support/faq/#gcm-not

Firebase and GCM are different but they can be used to achieve the same goals. Hope it helps you.

I don't think Firebase is currently equipped to handle this scenario. You need some sever side code to handle it. Either you could get hosting and make like a php endpoint what can used to incorporate the

[[FIRMessaging message]sendMessage:(nonnull NSDictionary *)message
                                to:(nonnull NSString *)receiver
                     withMessageID:(nonnull NSString *)messageID
                        timeToLive:(int64_t)ttl;

code and make it work, OR you need to find another service that can serve as the backend.

https://techcrunch.com/2016/02/02/batch-now-integrates-with-firebase-to-create-a-parse-alternative/

This Batch.com company seems to be the best solution that I have found so far. I have been able to have a users device send a json payload to an endpoint on their server that then sends Customized push notifications to specific targeted devices. It seems like Batch is specifically a Push Notification company, and it seems like the free basic plan is good enough to handle what you will need, silimar to how Parse worked.

Here is the actual code I wrote for sending the push notifications Objective C. (There is also a Swift 2 and Swift 3 example you can download from Batch.com)

NSURL *theURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.batch.com/1.1/(your API code here)/transactional/send"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];

[theRequest setValue:@"(your other API key here" forHTTPHeaderField:@"X-Authorization"];

NSDictionary *messageDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Hey This is a Push!", @"title", @"But it's a friendly push.  Like the kind of push friends do to each other.",@"body", nil];
NSArray *recipientsArray = [[NSArray alloc]initWithArray:someMutableArrayThatHasUsersFirebaseTokens];
NSDictionary *recipientsDict = [[NSDictionary alloc]initWithObjectsAndKeys:recipientsArray, @"custom_ids", nil];

NSDictionary *gistDict = @{@"group_id":@"just some name you make up for this pushes category that doesn't matter",@"recipients":recipientsDict,@"message":messageDict, @"sandbox":@YES};

NSError *jsonError;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gistDict options:NSJSONWritingPrettyPrinted error:&jsonError];

[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:jsonData];

NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:theRequest queue:queue1 completionHandler:^(NSURLResponse *response, NSData *POSTReply, NSError *error){
    if ([POSTReply length] >0 && error == nil){
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding:NSASCIIStringEncoding];  
            NSLog(@"BATCH PUSH FINISHED:::%@", theReply);
        });
    }else {
        NSLog(@"BATCH PUSH ERROR!!!:::%@", error);
    }
}];

Batch was pretty easy to install with Cocoa Pods.

I also used this code to get it working:

In app delegate:

@import Batch

In didFinishLaunching:

[Batch startWithAPIKey:@"(your api key)"]; // dev
[BatchPush registerForRemoteNotifications];

then later in app delegate:

- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:refreshedToken forKey:@"pushKey"];
    [defaults synchronize];


    BatchUserDataEditor *editor = [BatchUser editor];
    [editor setIdentifier:refreshedToken]; // Set to `nil` if you want to remove the identifier.
    [editor save];


    [self connectToFcm];

}

So thats how you do it, besides the setup and installation stuff which is all explained on the Batch.com website.

Once you get your token from firebase, you basically register it on Batch with

BatchUserDataEditor *editor = [BatchUser editor];
[editor setIdentifier:refreshedToken]; 
[editor save];

in App Delegate. Then when you want your users device1 to send a Push to another device2, assuming you have sent device1's custom id to device2 somehow, you can use that custom id to send the push notification payload to Batch.com's API, and Batch will handle the server side stuff to Apple APN and your Push notifications appear on device2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM