Skip to content

Users and installations

Alexander Boldyrev edited this page Oct 31, 2024 · 25 revisions

Table of contents

Terminology

Mobile Messaging SDK employs specific terms in order to address different type of information that you can synchronize towards Infobip Platform. You will see MMUser and MMInstallation terms in the SDK similarly to what you can see at People section at Infobip Portal.

Searching for user profile
  • MMInstallation is a specific installation of your application. Each application installation on a device receives unique installation ID - pushRegistrationId. pushRegistrationId is a permanent ID assigned to the app once it’s launched up until the moment it’s uninstalled from the device. In this documentation, the terms 'installation' and 'push registration' are used interchangeably and denote the same concept. You can see it as Mobile App Messaging (Push Notifications) destination under Contact Information tab of a user profile. A single user can have zero or more installations of different applications. You can change some specific settings of each installation of a user, add Custom attributes to it or do a remote Logout of a specific installation.
  • User represents a single person profile with Standard attributes, Custom attributes and Tags which you can set via the SDK.

Both user and installation objects are initialized once Mobile Messaging SDK is successfully started.

Installation

MMInstallation is a specific installation (or instance) of your application on a user's device. Standard attributes and their descriptions are available in docs, code - Installation. One user can have multiple installations. You can get current installation details from server:

MobileMessaging.fetchInstallation(completion: { installation, error in
    if let error = error {
        < handle error if not nil >
    } else {
        print("installation updated: \(installation)")
    }
})
expand to see Objective-C code

[MobileMessaging fetchInstallationWithCompletion:^(MMInstallation * _Nullable installation, NSError * _Nullable error) {
    if (error != nil) {
        < handle error if not nil >
    } else {
        NSLog(@"installation updated: %@)", installation);
    }
}];

All the current users installations are also available under user profile:

let installations: [MMInstallations]? = MobileMessaging.getUser()?.installations
expand to see Objective-C code

NSArray<MMInstallation *> *installations = [[MobileMessaging getUser] installations];

How to find a specific installation on Infobip Portal

Infobip creates an empty user profile as soon as device registers on the platform. Afterwards you should be able to find this user profile at Infobip Portal using for example pushRegistrationId (or other attributes, such as phone number, in case the installation was personalized) provided via the SDK: Searching for user profile

Enabling/disabling push registration

You can temporarily "disable" your installation if you don't want to receive push notifications:

if let installation = MobileMessaging.getInstallation() {
    installation.isPushRegistrationEnabled = false

    MobileMessaging.saveInstallation(installation, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

MMInstallation * installation = [MobileMessaging getInstallation];
if (installation != nil) {
    installation.isPushRegistrationEnabled = false;
    [MobileMessaging saveInstallation:installation completion:^(NSError * _Nullable error) {
        if (error != nil) {
            /* handle error if not nil */
        }
    }];
}

Setting installation as primary

On the Infobip account, a single user profile can have one or more mobile devices with the application installed. You might want to mark one of these devices as the primary device and send push messages only to this device (e.g. receive bank authorization codes only on one device). To achieve this and similar use-cases, you can utilize the APIs provided by the Mobile Messaging SDK.

For this feature to work, the API request for sending the push notification must include a special parameter targetOnlyPrimaryDevices set to true. Parameters for sending a single push notification can be checked in the Infobip API Docs. With this parameter, push notifications will not be sent to any installations that are not marked as primary. This means that for this feature to work, both the mobile implementation and the API request parameter must be used in conjunction.

By default, all installations are marked as non-primary. To set a particular installation as primary, either the Contact Information API or the following Mobile Messaging SDK API can be used:

if let installation = MobileMessaging.getInstallation() {
    installation.isPrimaryDevice = true

    MobileMessaging.saveInstallation(installation, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

MMInstallation * installation = [MobileMessaging getInstallation];
if (installation != nil) {
    installation.isPrimaryDevice = true;
    [MobileMessaging saveInstallation:installation completion:^(NSError * _Nullable error) {
        if (error != nil) {
            /* handle error if not nil */
        }
    }];
}

You can set/reset primary setting for any other installation of a current user:

let pushRegId = < Push Registration ID of another installation >
MobileMessaging.setInstallation(withPushRegistrationId: pushRegId, asPrimary: false, completion: { installations, error in
    if let error = error {
        < handle error if not nil >
    } else {
        print("installations updated: \(installations)")
    }
})
expand to see Objective-C code

NSString *pushRegId = < Push Registration ID of another installation >;
[MobileMessaging setInstallationWithPushRegistrationId:pushRegId asPrimary:false completion:^(NSArray<MMInstallation *> * _Nullable installations, NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    } else {
        NSLog(@"installations updated: %@", installations);
    }
}];

Custom attributes

An Installation can have custom attributes in the same way as User does. Custom installation attributes allow you to target specific installations of the same user.

if let installation = MobileMessaging.getInstallation() {
    installation.customAttributes = ["OneTimePasswords" : true as NSNumber]

    MobileMessaging.saveInstallation(installation, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

MMInstallation * installation = [MobileMessaging getInstallation];
if (installation != nil) {
    installation.customAttributes = @{@"OneTimePasswords" : @YES};
    [MobileMessaging saveInstallation:installation completion:^(NSError * _Nullable error) {
        if (error != nil) {
            /* handle error if not nil */
        }
    }];
}

These custom attributes can be seen under push destination card on a portal: Custom attributes of an installation

User

You can provide additional user's data to the server, so that you will be able to send personalised targeted messages to exact user and have other nice features. Library supports a set of predefined attributes as well as custom ones.

You can always get current user data from server via the SDK API. The request produce an HTTP call, so make sure to handle failures if any.

MobileMessaging.fetchUser(completion: { user, error in
    if let error = error {
        < handle error if not nil >
    } else {
        print("user fetched: \(user)")
    }
})
expand to see Objective-C code

[MobileMessaging fetchUserWithCompletion:^(MMUser * _Nullable user, NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    } else {
        NSLog(@"user fetched", user)
    }
}];

Personalization: external user ID, emails and phone numbers

Each user can have External user ID, Emails and Phone numbers. These fields are unique identifiers of a user profile on Infobip platform and provide capability to personalize any app installation with a user profile. The platform provides data grouping functions based on these parameters. For example, if two installations of a particular app will try to save the same Extrenal User ID, then both of them will be collected under a single user. Phone number, Email and External user ID are also widely used when targeting users with messages across different channels via Infobip platform.

Following restrictions apply:

It is also possible to set User attributes on personalization using UserAttributes. It will override any existing values, so use carefully.

let userIdentity = MMUserIdentity(externalUserId: "ExternalId")
//OR
//let userIdentity = MMUserIdentity(phones: ["38516419710"])
//replaces existing values set to the person with provided ones
let userAttributes = MMUserAttributes(firstName: "John", middleName: nil, lastName: "Doe", tags: ["Promotions", "Transactions"], genderNonnull: .Male, birthday: Date(fromString: "01.01.1970"))
MobileMessaging.personalize(withUserIdentity: userIdentity, userAttributes: userAttributes, completion: { error in
    if let error = error {
        < handle error if not nil >
    }
})
expand to see Objective-C code

MMUserIdentity *userIdentity = [[MMUserIdentity alloc] initWithExternalUserId:"ExternalId"];
// OR
// MMUserIdentity *userIdentity = [[MMUserIdentity alloc] initWithPhones:@[@"38516419710"] emails:@[@"john.doe@infobip.com"] externalUserId:"ExternalId"];
[MobileMessaging personalizeWithUserIdentity:userIdentity userAttributes:nil completion:^(NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    }
}];

External User ID

You can use External User ID to uniquely target your user. External User ID is meant to be an ID of a user in an external (non-Infobip) service. It can be any string and can be shared across different instances of your app, so that a user with multiple devices can still be targeted as a single user of your app. Notice: for externalUserId any string values such as "null", "Null" or "NULL" are not supported and would be considered as JSON null.

Depersonalization

You can depersonalize current installation to detach it from current user profile so that the user won't receive messages when targeted by any person attribute:

MobileMessaging.depersonalize(completion: { status, error in
    if let error = error {
        < handle error if not nil >
    } else {
        print("installations depersonalized, status: \(status)")
    }
})
expand to see Objective-C code

[MobileMessaging depersonalizeWithCompletion:^(enum MMSuccessPending status, NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    } else {
        NSLog(@"Installation depersonalized, status: %ld", (long)status);
    }
}];

You also can depersonalize any installation that is personalized with the current user (perform remote logout):

let currentUser = MobileMessaging.getUser()
let pushRegId = currentUser?.installations?.< filter the one appropriately >.pushRegistrationId
MobileMessaging.depersonalizeInstallation(withPushRegistrationId: pushRegId, completion: { installations, error in
    if let error = error {
        < handle error if not nil >
    } else {
        print("installations updated: \(installations)")
    }
})
expand to see Objective-C code

MMUser *currentUser = [MobileMessaging getUser];
NSString *pushRegId = currentUser.intallations.< filter the one appropriately >.pushRegistrationId;
[MobileMessaging depersonalizeInstallationWithPushRegistrationId:pushRegId completion:^(NSArray<MMInstallation *> * _Nullable installations, NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    } else {
        NSLog(@"Installation updated %@", installations);
    }
}];

Q: When should I depersonalize my users installations?

A: Installation can (and probably should) be depersonalized if the app meets all the following conditions:

  • you leverage user attributes functionality
  • your application has "log out"/"sign out" feature
  • you don't want a newly logged in (signed up) user to be targeted by other user's data (such as phone numbers, first name, custom attributes etc.) and receive personalized messages
  • you want logged out (signed out) user to still receive broadcast notifications (if not, you need to disable push registration)

Personalize with force depersonalization

If you want previous personalization to be reset, in other words, depersonalize this particular installation, provide a special argument forceDepersonalize:

let userIdentity = MMUserIdentity(externalUserId: "ExternalUserId")
let userAttributes = MMUserAttributes(firstName: "John", middleName: nil, lastName: "Doe", ...)
MobileMessaging.personalize(forceDepersonalize: true, userIdentity: userIdentity, userAttributes: userAttributes, completion: { error in
    if let error = error {
        < handle error if not nil >
    }
})
expand to see Objective-C code

MMUserIdentity *userIdentity = [[MMUserIdentity alloc] initWithExternalUserId:"ExternalUserId"];
MMUserAttributes *userAttributes = [[MMUserAttributes alloc] initWithFirstName:@"John" middleName:nil lastName:@"Doe" tags:nil genderNonnull:MMGenderNonnullUndefined birthday:nil customAttributes:nil];
[MobileMessaging personalizeWithForceDepersonalize:true userIdentity:userIdentity userAttributes:userAttributes completion:^(NSError * _Nullable error) {
    if (error != nil) {
        /* handle error if not nil */
    }
}];

Personalize but keep profile as Lead

If you want to do a personalization without promoting profile to Customer you can set keepAsLead parameter to true.

MobileMessaging.personalize(withUserIdentity: userIdentity, userAttributes: userAttributes, keepAsLead: true, completion: { error in
     if let error = error {
        < handle error if not nil >
    }
})

User types (roles)

There are two types of user profiles: Lead and Customer:

Leads

Leads are profiles with the person's name and contact information that have not been verified.

Customers

Leads are changed to Customers during personalization using the provided identifiers. If profile is already a Customer, profile is updated with the information about the installation.

let type = MobileMessaging.getUser()?.type //LEAD or CUSTOMER  

Standard attributes

You can set different standard attributes of a user, such as First name, Last name, Birthday etc.:

if let user = MobileMessaging.getUser() {
    user.firstName = "John"
    user.lastName = "Doe"
    user.gender = .Male
    user.birthday = Date(fromString: "01.01.1970")

    MobileMessaging.saveUser(user, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

MMUser *user = [MobileMessaging getUser];
if (user != nil) {
    user.firstName = @"John";
    user.lastName = @"Doe";
    user.genderNonnull = MMGenderNonnullMale;
    user.birthday = [Date fromString: @"01.01.1970"];

    [MobileMessaging saveUser:user completion:^(NSError * _Nullable error) {
        if (error != nil) {
            /* handle error if not nil */
        }
    }];
}

Please note that saveUser() may return a USER_MERGE_INTERRUPTED error if you have provided an already existing Phone number, Email, or External User Id that are already taken by another existing user profile. In other words, that particular phone/email/externalUserId is a unique identifier of an already existing user, different from the one that this installation is currently personalized with. You can find more details about this, and other possible errors at Server errors. If you wish to personalize the app installation with another existing user, that is, merge current user with another one, please use our Personalize API or SDK method.

For editing any attributes of the existing user, perform fetchUser first to get server data. Setting values to null (and saving user afterwards) will remove them from the user.

Custom attributes

Apart from list of standard attributes, each MMUser can have a set of custom ones. Custom attributes commonly used to cover those use-cases about targeting and segmentation that are not supported by the platform out of the box. Custom attributes are key-value pairs. Keys are of string types, values can be of number, boolean, date, dateTime or list of objects data types.

Difference between date and datetime types is that usage of date doesn't sync time to the server (e.g. "2020-11-30"), but with datetime we provide timestamp as well that can be visible on web.

You can easily update custom attributes of a user as follows:

if let user = MobileMessaging.getUser() {
    user.customAttributes = [
        "favoriteMeal"      : "pizza"   as NSString,
        "bootSize"          : 9.5       as NSNumber,
        "isSubscribed"      : true      as NSNumber
        "height"            : NSNull(), // this way data will be erased on server
        "installationDate"  : NSDate(),
        "lastVisitDateTime" : MMDateTime(date: Date()],
        "favsList"          : [
            ["id": "1", "price": 99.99, "sale": true],
            ["id": "2", "price": 149.99, "sale": false],
        ] as NSArray
    ]

    MobileMessaging.saveUser(user, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

    MMUser *user = [MobileMessaging getUser];
    if (user != nil) {
        user.customAttributes = @{
            @"favoriteMeal"     : @"pizza",
            @"bootSize"         : @9.5,
            @"isSubscribed"     : @YES,
            @"height"           : [NSNull null],
            @"installationDate" : [NSDate date],
            @"lastVisitDateTime": [[MMDateTime alloc] initWithDate: [NSDate date]],
            @"favsList"         : @[
                    @{@"id": @"1", @"price": @99.99, @"sale": @YES},
                    @{@"id": @"2", @"price": @149.99, @"sale": @NO}
            ]
        };
        
        [MobileMessaging saveUser:user completion:^(NSError * _Nullable error) {
            if (error != nil) {
                /* handle error if not nil */
            }
        }];
    }

And you can get current values of the custom attributes as well:

let user = MobileMessaging.getUser()
let favoriteMeal = user?.customAttributes?["favoriteMeal"] as? NSString
let bootSize = (user?.customAttributes?["bootSize"] as? NSNumber)?.doubleValue
let isSubscribed = (user?.customAttributes?["isSubscribed"] as? NSNumber)?.boolValue
let installationDate = user?.customAttributes?["installationDate"] as? NSDate
let lastVisitDateTime = user?.customAttributes?["lastVisitDateTime"] as? MMDateTime
let favsList = user?.customAttributes?["favsList"] as? NSArray
expand to see Objective-C code

MMUser *user = [MobileMessaging getUser];
NSString *favoriteMeal = (NSString *)user.customAttributes[@"favoriteMeal"];
double bootSize = [(NSNumber *)user.customAttributes[@"bootSize"] doubleValue];
BOOL isSubscribed = [(NSNumber *)user.customAttributes[@"isSubscribed"] boolValue];
NSDate *installationDate = (NSDate *)user.customAttributes[@"installationDate"];
MMDateTime *lastVisitDateTime = (MMDateTime *)user.customAttributes[@"lastVisitDateTime"];
NSArray *favsList = (NSArray *)user.customAttributes[@"favsList"];

With this data, you can segment users by using Segments and target them by their custom attribute values: Create a Segment

List of objects

Detailed description on what list of objects is, some common use cases and how to set it on web are provided here. Mobile implementation specifics:

  • as provided in the upper example of updating custom attributes, list of objects can be set as a custom attribute, but this type is more complex
  • list of objects needs to be created on web
  • it needs to have the same structure as on web when it's provided from SDK, otherwise error will be returned as an error response
  • supported types are: string, number, boolean, date and datetime

Tags

You can add or remove Tags from users based on their preferences or interests. Using Tags you can easily segment users which are interested in any specific topic and send messages only to such users.

if let user = MobileMessaging.getUser() {
    user.tags = ["Promotions", "Transactions"]

    MobileMessaging.saveUser(user, completion: { error in
        if let error = error {
            < handle error if not nil >
        }
    })
}
expand to see Objective-C code

MMUser *user = [MobileMessaging getUser];
if (user != nil) {
    user.tags = @[@"Promotions", @"Transactions"];
    [MobileMessaging saveUser:user completion:^(NSError * _Nullable error) {
        if (error != nil) {
            /* handle error if not nil */
        }
    }];
}

Afterwards you will see these tags in a user profile and will be able to segment such users when sending targeted messages or campaigns. Broadcast by tag

User data storage

By default, user data is stored on a device, so it can be available even when the device is offline. Also, we store unreported user data, so we can automatically retry sending it to our server. In order to change default behaviour and disable storing user data, do as follows:

MobileMessaging.privacySettings.userDataPersistingDisabled = true
Clone this wiki locally