SimpleSample-users-ios

Ask tech team
From QuickBlox Developers (API docs, code samples, SDK)
Jump to: navigation, search


Contents

Sources

Project homepage on GIT — https://github.com/QuickBlox/quickblox-ios-sdk/tree/master/sample-users

Download ZIP - https://github.com/QuickBlox/quickblox-ios-sdk/archive/master.zip



Overview

This sample demonstrates how to work with Users QuickBlox module.
It allows you to see all users, their details, create user, search user, edit current user, sign in, sign out, use social networks (Facebook, Twitter)

It shows you how to:

  1. Retrieve all users
  2. Get users' details
  3. Edit user's parameters
  4. Search users
  5. Sign Up, Sign In/Sign out
  6. How to use QuickBlox through social networks (Facebook, Twitter)




Guide: Getting Started with Users API

Getting a QuickBlox account

http://admin.quickblox.com/register

Creating an application on the Admin panel

http://admin.quickblox.com/apps/new

For further reading, there is also this 5 minute guide.

Connecting QuickBlox to your application

To get the information on how to connect to the QuickBlox.framework, please, refer to the IOS-how-to-connect-Quickblox-framework page.

NEW! CocoaPods integration in Users sample

QuickBlox framework is linked to the Users sample project using CocoaPods. You could easily add QuickBlox to any project that already uses CocoaPods. Just add to your Podfile:
pod 'QuickBlox'

And run pod install

Adding a User Base to your application

Signing Up

Creating a new User (registration)

Only login/email and password fields are required

QBUUser *user = [QBUUser user];
user.password = @"password";
user.login = @"login";
 
// Registration/sign up of User
[QBRequest signUp:user successBlock:^(QBResponse *response, QBUUser *user) {
    // Sign up was successful
} errorBlock:^(QBResponse *response) {
    // Handle error here
}];

If registration was successful - you can sign in using you login/email and password.

Signing In & Social authorization

There are 4 methods that you can use to sign in to QuickBlox:

  • Signing In with a login & password
  • Signing In with an email & password
  • Signing In using a Facebook/Twitter access token
  • Signing In with Twitter Digits


Signing In with a login & password

- (void)login {
 
    // Authenticate user
    [QBRequest logInWithUserLogin:@"login"
                         password:@"password"
                     successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nullable user)
     {
         // Login succeeded
 
     } errorBlock:^(QBResponse * _Nonnull response) {
         // Handle error
     }];
}

Signing In with an email & password

[QBRequest logInWithUserEmail:@"email@email.me"
                     password:@"password"
                 successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nullable user)
 {
     // Login succeeded
 
 } errorBlock:^(QBResponse * _Nonnull response) {
     // Handle error
 }];

Signing In using a Facebook/Twitter access token

There are lots of use cases where this API will be helpful. For example, Twitter framework (iOS5) or Social Framework (iOS6).

For example, you can set the Twitter account in your device Settings, and use it for tweets like this:

TwitteriOS5-6.jpeg

And if you want to use this account to login to QuickBlox, you need to retrieve access token & access the token secret. There is one Twitter official solution: Using Reverse Auth. Just use it to retrieve your credentials and then you will be able to sign in to QuickBlox using your Twitter system account.

[QBRequest logInWithSocialProvider:@"facebook" accessToken:@"facebook_access_token" accessTokenSecret:nil successBlock:^(QBResponse *response, QBUUser *user) {
    // Login succeded
} errorBlock:^(QBResponse *response) {
    // Handle error
}];
[QBRequest logInWithSocialProvider:@"twitter" accessToken:@"twitter_access_token" accessTokenSecret:@"twitter_token_secret" successBlock:^(QBResponse *response, QBUUser *user) {
    // Login succeded
} errorBlock:^(QBResponse *response) {
    // Handle error
}];

Signing In with Twitter Digits (deprecated)

Warning! As announced at Google I/O, Digits is being replaced with Firebase phone authentication.

Digits lets people create an account or sign into your app using nothing but their phone number on iOS and Android. Built using the same global, reliable infrastructure Twitter uses, Digits will verify the user’s phone number with a simple customizable user interface that easily integrates into your app.

Read more how to start with Twitter Digits https://docs.fabric.io/ios/digits/digits.html


- (void)loginWithTwitterDigits {
    NSString* phoneNumber = @"4590882333";
 
    [[Digits sharedInstance] authenticateWithPhoneNumber:phoneNumber
                                        digitsAppearance:nil
                                          viewController:nil
                                                   title:nil
                                              completion:[self completion]];
}
 
- (DGTAuthenticationCompletion)completion
{
    return ^(DGTSession *session, NSError *error) {
        DGTOAuthSigning *oauthSigning = [[DGTOAuthSigning alloc] initWithAuthConfig:[Digits sharedInstance].authConfig
                                                                        authSession:session];
 
        NSDictionary *authHeaders = [oauthSigning OAuthEchoHeadersToVerifyCredentials];
		if (!authHeaders) {
			NSLog(@"error: no authHeaders"); // user seems skipped auth process
			return;
		}
        [QBRequest logInWithTwitterDigitsAuthHeaders:authHeaders successBlock:^(QBResponse *response, QBUUser *user) {
            NSLog(@"Logged in with twitter digits!");
        } errorBlock:^(QBResponse *response) {
            NSLog(@"Response error: %@", response.error);
        }];
    };
}

Signing In with Firebase phone

You have to start with this guide and obtain Firebase user ID token (access token) https://firebase.google.com/docs/auth/ios/phone-auth

Then you can pass it into QuickBlox login method:

[QBRequest logInWithFirebaseProjectID:projectId accessToken:accessToken successBlock:^(QBResponse *response, QBUUser *user) {
            NSLog(@"Logged in with twitter digits!");
        } errorBlock:^(QBResponse *response) {
            NSLog(@"Response error: %@", response.error);
        }];

If you are migrating from Twitter Digits - use this guide https://docs.fabric.io/apple/digits/apple-migration.html

Online\Offline status

Each user has the lastRequestAt field - the last user activity time (last query time). You can use it to determine if user online or offline now. For example:

Date format used for last_request_at, created_at and updated_at must be yyyy-mm-dd or yyyy.mm.dd

QBUUser *user = ...;
 
NSInteger currentTimeInterval = [[NSDate date] timeIntervalSince1970];
NSInteger userLastRequestAtTimeInterval   = [[user lastRequestAt] timeIntervalSince1970];
 
// if user didn't do anything last 1 minute (60 seconds)    
if((currentTimeInterval - userLastRequestAtTimeInterval) > 60){ 
     // user is offline now
}

It's also possible to get a list of online users:

NSMutableDictionary *filters = [NSMutableDictionary dictionary];
filters[@"filter[]"] = @"date last_request_at gt 2012-03-20T08:47:34Z";
 
[QBRequest usersWithExtendedRequest:filters page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:100] successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
     // Request succeeded   
} errorBlock:^(QBResponse *response) {
     // Handle error  
}];

Current User

After user logged in you can access current user:

[QBSession currentSession].currentUser

Update your own profile

If you want to update your profile - just use the method below. You can update only your own user, just put your User's ID:

QBUpdateUserParameters *updateParameters = [QBUpdateUserParameters new];
updateParameters.website = @"www.mysite.com";
updateParameters.phone = @"8234234";
updateParameters.tags = @[@"man", @"golf"];
 
[QBRequest updateCurrentUser:updateParameters successBlock:^(QBResponse *response, QBUUser *user) {
    // User updated successfully
} errorBlock:^(QBResponse *response) {
    // Handle error
}];

Custom data

It's possible to attach custom parameters to the user using customData property:

QBUpdateUserParameters *updateParameters = [QBUpdateUserParameters new];
updateParameters.customData = @"my custom data"; // can contain JSON or any other formats
...

Updating a profile picture (avatar)

To update a user profile picture you must:

  1. Upload new picture to Content module
  2. Connect picture to user through user's blobID field
// Upload new avatar to Content module
NSData *avatar = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myAvatar" ofType:@"png"]];
//
[QBRequest TUploadFile:avatar fileName:@"MyAvatar" contentType:@"image/png" isPublic:NO successBlock:nil statusBlock:nil errorBlock:nil];

Now other users will be able to see your avatar.

NSUInteger userProfilePictureID = user.blobID; // user - an instance of QBUUser class
 
// download user profile picture
[QBRequest downloadFileWithID:userProfilePictureID successBlock:nil statusBlock:nil errorBlock:nil];

To delete the user's file just set -1 to blobID field.

Reset a password

If your forgot your password - you can reset it using the method below. An email with instructions will be sent to your email address.

Resetting a User's password.

// Reset User's password with email
[QBRequest resetUserPasswordWithEmail:@"test@test.te" successBlock:^(QBResponse *response) {    
    // Reset was successful
} errorBlock:^(QBResponse *response) {
    // Error
}];

Signing Out

If you want to sign out - just use the method below:

Removing a User's session (logout)

[QBRequest logOutWithSuccessBlock:^(QBResponse *response) {
    // Successful logout
} errorBlock:^(QBResponse *response) {
    // Handle error
}];


Retrieving users

There are lots of methods for retrieving users:

  • Retrieve all Users
  • Retrieve Users by IDs
  • Retrieve Users by Logins
  • Retrieve Users by Emails
  • Retrieve Users by Phone numbers
  • Retrieve Users by Twitter IDs
  • Retrieve Users by Facebook IDs
  • Retrieve Users by Tags. Tags like groups, in which we can group users
  • Retrieve Users with full name
  • Retrieve User by ID
  • Retrieve User by login
  • Retrieve User by Facebook ID
  • Retrieve User by Twitter ID
  • Retrieve User by email
  • Retrieve User by external ID. You can connect a user from a 3d party system to a QuickBlox user through an external ID.

Retrieving all Users

// Number of page you want to fetch + number of items in this page
QBGeneralResponsePage *page = [QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10];
 
[QBRequest usersForPage:page successBlock:^(QBResponse *response, QBGeneralResponsePage *pageInformation, NSArray *users) {
    // Successful response contains current page infromation + list of users
} errorBlock:^(QBResponse *response) {
    // Handle error
}];

Sometimes you need to retrieve all your QuickBlox users. But there is one restriction: you can retrieve a maximum of 100 users per query.

Here is an example how to retrieve all users:

- (void)retrieveAllUsersFromPage:(int)page{
 
    [QBRequest usersForPage:[QBGeneralResponsePage responsePageWithCurrentPage:page perPage:100] successBlock:^(QBResponse *response, QBGeneralResponsePage *pageInformation, NSArray *users) {
        userNumber += users.count;
        if (pageInformation.totalEntries > userNumber) {
            [self retrieveAllUsersFromPage:pageInfromation + 1];
        }
    } errorBlock:^(QBResponse *response) {
        // Handle error
    }];
}
 
// Start
[self retrieveAllUsersFromPage:1];

It's possible to use some filters and sort parameters:

NSMutableDictionary *filters = [NSMutableDictionary dictionary];
filters[@"order"] = @"desc date last_request_at";
 
[QBRequest usersWithExtendedRequest:filters page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10] successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
     // Request succeeded   
} errorBlock:^(QBResponse *response) {
     // Handle error  
}];

Retrieve Users by IDs

[QBRequest usersWithIDs:@[@300,@298] page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10] successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
    // Successful response with page information and users array
} errorBlock:^(QBResponse *response) {
    // Handle error here
}];

Retrieving Users through their Logins

[QBRequest usersWithLogins:@[@"login1", @"login2"] page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10]
              successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
                  // Successful response with page information and users array
              } errorBlock:^(QBResponse *response) {
                  // Handle error
              }];

Retrieving Users through their Emails

[QBRequest usersWithEmails:@[@"email1@email.email", @"email2@email.email"]
                      page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10]
              successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
        // Successful response with page information and users array
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Retrieving Users through their Twitter IDs

[QBRequest usersWithTwitterIDs:@[@"twitterId1", @"twitterId2"] page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10] successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
        // Successful response with page information and users array
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Retrieving Users through their Facebook IDs

[QBRequest usersWithFacebookIDs:@[@"facebookId1", @"facebookId2"] page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10]
                   successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
                           // Successful response with page information and users array
                   } errorBlock:^(QBResponse *response) {
                           // Handle error
                   }];

Retrieving Users by tags

[QBRequest usersWithTags:@[@"tag1", @"tag2"] page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10]
            successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
                      // Successful response with page information and users array
} errorBlock:^(QBResponse *response) {
                      // Handle error
}];

Retrieving Users through their full names

[QBRequest usersWithFullName:@"Full Name" page:[QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:10]
                successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users) {
                        // Successful response with page information and users array
                } errorBlock:^(QBResponse *response) {
                        // Handle error
                }];

Retrieving User by id

[QBRequest userWithID:1326 successBlock:^(QBResponse *response, QBUUser *user) {
        // Successful response with user
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Retrieving User by facebook ID

[QBRequest userWithFacebookID:@"facebookId" successBlock:^(QBResponse *response, QBUUser *user) {
        // Successful response with user
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Retrieving User through twitter ID

[QBRequest userWithTwitterID:@"twitterId" successBlock:^(QBResponse *response, QBUUser *user) {
        // Successful response with user
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Retrieving User through an external ID

[QBRequest userWithExternalID:130 successBlock:^(QBResponse *response, QBUUser *user) {
        // Successful response with user
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Deleting current user

If you need, you can delete current user using a method below:

Deleting a User through ID

[QBRequest deleteCurrentUserWithSuccessBlock:^(QBResponse *response) {
        // Successful response with user
} errorBlock:^(QBResponse *response) {
        // Handle error
}];

Integrating QuickBlox with your existing User Base

If you want to integrate QuickBlox, but you have already your User Base, you can use the externalUserID field. Just set it during the QuickBlox user registration:

QBUUser *user = [QBUUser user];      
user.login = @"Javck";
user.password = @"javckpassword";
user.externalUserID = 758902384; // ID of user from your own user base
 
[QBRequest signUp:user successBlock:^(QBResponse *response, QBUUser *user) {
    // Sign up was successful
} errorBlock:^(QBResponse *response) {
    // Handle error here
}];

Next you can retrieve QuickBlox user by external ID by user ID from your user base and use QuickBlox platform features.

Address Book

Upload Address Book

For upload address book use code bellow:

QBAddressBookContact *contact = [QBAddressBookContact new];
contact.name = @"Apple service";
contact.phone = @"1-800-275-2273";
 
NSMutableOrderedSet<QBAddressBookContact *>* addressBook = [NSMutableOrderedSet orderedSet];
[addressBook addObject:contact];
 
[QBRequest uploadAddressBookWithUdid:nil //or device udid
                         addressBook:[addressBook copy]
                               force:NO
                        successBlock:^(QBAddressBookUpdates *updates) {
                        } errorBlock:^(QBResponse *response) {
                        }];
  • You also can edit an existing contact by providing new name for it.
  • You also can upload more contacts, not just all in one request - they will be added to your address book on the backend. If you want to override the whole address book on the backend - just provide force:YES.
  • You also can remove a contact by setting contact.destroy = YES.

A device UDID is used in cases where user has 2 or more devices and contacts sync is off. Otherwise - user has a single global address book.

Retrieving Address Book

For retrieve Address Book use code bellow:

[QBRequest addressBookWithUdid:nil
                  successBlock:^(NSArray<QBAddressBookContact *> * _Nonnull contacts) {
                  } errorBlock:^(QBResponse * _Nonnull response) {
                  }];