Apple Ramos
Apple Ramos

Reputation: 275

Send tag to OneSignal after log in

I want to send tag to a specific user after he/she logged in so he/she can receive notifications. Only logged in users will receive notifications. When he/she logs out, I will delete his/her tag. How can I do this?

My code in AppDelegate:

let oneSignal: OneSignal = OneSignal(launchOptions: launchOptions, appId: "<my-app-id>") {
        (message, additionalData, isActive) in

        if (additionalData != nil) {
            NSLog("APP LOG ADDITIONALDATA: %@", additionalData);
            let displayMessage: NSString = NSString(format:"NotificationMessage:%@", message);

            var messageTitle: NSString = "";
            if (additionalData["discount"] != nil) {
                messageTitle = additionalData["discount"] as String
            }
            else if (additionalData["bonusCredits"] != nil) {
                messageTitle = additionalData["bonusCredits"] as String;
            }
            else if (additionalData["actionSelected"] != nil) {
                messageTitle = NSString(format:"Pressed ButtonId:%@", additionalData["actionSelected"] as String);
            }

            var alertView: UIAlertView = UIAlertView(title: messageTitle,
                message:displayMessage,
                delegate:self,
                cancelButtonTitle:"Close");

            alertView.show();
        }

        else if (isActive) {
            var alertView: UIAlertView = UIAlertView(title:"OneSignal Message",
                message:message,
                delegate:self,
                cancelButtonTitle:"Close");
            alertView.show();
        }
    }

My code in my LogInViewController:

let oneSignal = OneSignal()
oneSignal.sendTag("username", value: self.usernameTextField.text)

The code in my appDelegate is working fine, my users already receive notifications. But they can receive notifications even if they're not logged in.

Upvotes: 13

Views: 7474

Answers (2)

Ramesh sambu
Ramesh sambu

Reputation: 3539

Objective-C:

// Send tag: After login 
[OneSignal sendTag:@"key" value:@"value"];      

// Delete tag: After logout
[OneSignal deleteTag:@"key"];

Swift:

// Send tag: After login
OneSignal.sendTag("key", value: "value") // for sending that is inserting tag in OneSignal

// Delete tag: After logout
OneSignal.deleteTag("key")  // delete that specific tag from OneSignal db

Upvotes: 2

jkasten
jkasten

Reputation: 3948

You need to use the same oneSignal instance from AppDelegate in your LogInViewController. You can make oneSignal static at the class level so it can be shared between both classes.

To delete a tag you can call oneSignal.deleteTag("username")

Update: As of the iOS 2.0 SDK all methods on the OneSignal class are now static.

Upvotes: 9

Related Questions