Stackmob

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

Contents

StackMob to QuickBlox Tutorial

Why QuickBlox?

QuickBlox provides 2 big feature-sets:

  1. Complete backend service for your mobile apps with datastore, push notification services, location features and content storage.
  2. Communication platform with instant messaging, video chat, audio chat and augmented reality.


Use our iOS, Android, and Javascript SDKs to add powerful communication features to your app and use our data services for your backend.

Take a quick look into QuickBlox modules and features http://quickblox.com/modules


If you're looking to switch from StackMob, have no fear; we'll provide a quick comparison of features from their SDK to those found in the QuickBlox SDKs. From the code examples, you'll see that making the switch to QuickBlox is really easy.

For the full SDK reference, check out our:

  1. Quickblox iOS SDK documentation
  2. Quickblox Android SDK documentation
  3. Quickblox Web SDK documentation
  4. Quickblox REST API documentation

Getting Started

With StackMob, you initialize an instance of SMClient, using only your public key, as well as an instance of SMCoreDataStore (for iOS). For Android - initialize an instance of StackMobAndroid, using only your public key:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Declare a variable in your AppDelegate.h file called SMClient *client;
  self.client = [[SMClient alloc] initWithAPIVersion:@"0" publicKey:@"YOUR_PUBLIC_KEY"];
  self.coreDataStore = [self.client coreDataStoreWithManagedObjectModel:self.manangedObjectModel];
 
  ...
}
public void onCreate() { 
 
    ...
 
    StackMobAndroid.init(getApplicationContext(), 0, "9844010e-094f-4b5a-b784-530275cf452b");
 
    ...
}

With QuickBlox you initialize framework with application credentials. Use the QuickBlox 5 mins guide to register your QuickBlox application and get the credentials:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [QBSettings setApplicationID:92];
    [QBSettings setAuthorizationKey:@"wJHdOcQSxXQGWx5"];
    [QBSettings setAuthorizationSecret:@"BTFsj7Rtt27DAmT"];
 
    ...
}
public void onCreate() { 
 
    ...
 
    QBSettings.getInstance().fastConfigInit("961", "PBZxXW3WgGZtFZv", "vvHjRbVFF6mmeyJ");
 
    ...
}

Custom objects

Use QuickBlox Custom Objects Android and iOS samples to get more info.

Creating objects

With StackMob, you can extend the StackMobModel class for your objects (for Android). For iOS - simply create a new Managed Object, and call save on the Managed Object Context:

NSManagedObjectContext *context = self.coreDataStore contextForCurrentThread];
NSManagedObject *gameScore = [NSEntityDescription insertNewObjectForEntityForName:@"Gamescore" inManagedObjectContext:context];
[gameScore setValue:[gameScore assignObjectId] forKey:[gameScore primaryKeyField]];
[gameScore setValue:[NSNumber numberWithInt:1337] forKey:@"score"];
[gameScore setValue:@"Sean Plott" forKey:@"playerName"];
[gameScore setValue:[NSNumber numberWithBool:NO] forKey:@"cheatMode"];
 
[context saveOnSuccess:^{
    // The gameScore saved successfully.
} onFailure:^(NSError *error) {
    // There was an error saving the gameScore.
}];
package com.example.yourapp;
import java.util.Date;
import com.stackmob.sdk.model.StackMobModel;
 
public class GameScore extends StackMobModel {
 
    private int score;
    private String playerName;
    private boolean cheatMode;
 
    public GameScore(int score, String playerName, boolean cheatMode) {
        super(GameScore.class);
        this.score = score;
        this.playerName = playerName;
        this.cheatMode = false;
    }
}
 
...
 
// Then create
GameScore gameScore = new GameScore(1337, "Carl Atupem", false);
gameScore.save(new StackMobModelCallback() {
    @Override
    public void success() {
        // the call succeeded
    }
 
    @Override
    public void failure(StackMobException e) {
        // the call failed
    }
});

With QuickBlox it's a piece of cake to create an object:

QBCOCustomObject *object = [QBCOCustomObject customObject];
object.className = @"Movie"; // your Class name
 
// Object fields
[object.fields setObject:@"Star Wars" forKey:@"name"];
[object.fields setObject:[NSNumber numberWithFloat:9.1f] forKey:@"rating"];
[object.fields setObject:[NSNumber numberWithBool:NO] forKey:@"documentary"];
[object.fields setObject:@"fantasy" forKey:@"genre"];
[object.fields setObject:@"Star Wars is an American epic space opera franchise consisting of a film series created by George Lucas." forKey:@"descriptions"];
 
[QBCustomObjects createObject:object delegate:self];
 
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Create record result
    if(result.success && [result isKindOfClass:QBCOCustomObjectResult.class]){        
        QBCOCustomObjectResult *createObjectResult = (QBCOCustomObjectResult *)result;
         NSLog(@"Created object: %@", createObjectResult.object);        
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}
// Object fields
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("name", "Star Wars");
fields.put("comment", "Star Wars is an American epic space opera franchise consisting of a film series created by George Lucas.");
fields.put("genre", "fantasy");
 
QBCustomObject qbCustomObject = new QBCustomObject();
qbCustomObject.setClassName("Movie");  // your Class name
qbCustomObject.setFields(fields);
QBCustomObjects.createObject(qbCustomObject, new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        if (result.isSuccess()) {
            QBCustomObjectResult qbCustomObjectResult = (QBCustomObjectResult) result;
            QBCustomObject qbCustomObject = qbCustomObjectResult.getCustomObject();
            Log.d("New record: ",newCustomObject.toString());
        } else {
            Log.e("Errors",result.getErrors().toString());
        }
    }
});

Querying objects

With StackMob you use the StackMobQuery class to search for objects (for Android). For iOS - simply execute a Core Data fetch request:

NSFetchRequest *playerFetch = [[NSFetchRequest alloc] initWithEntityName:@"Gamescore"];
[playerFetch setPredicate:[NSPredicate predicateWithFormat:@"playerName == 'Carl Atupem'"]];
 
NSManagedObjectContext *context = self.coreDataStore contextForCurrentThread];
[context executeFetchRequest:playerFetch onSuccess:^(NSArray *results) {
 
    // The find succeeded.
    NSLog(@"Successfully retrieved %i scores.", results.count);
} onFailure:^(NSError *error) {
 
    // Log details of the failure
    NSLog(@"Error: %@", error); 
}];
GameScore.query(GameScore.class, new StackMobQuery().field(new StackMobQueryField("playerName")
.isEqualTo("Carl Atupem")), new StackMobQueryCallback<GameScore>() {
    @Override
    public void success(List<GameScore> result) {
       // You've now got a list game scores
    }
 
    @Override
    public void failure(StackMobException e) {
    }
});


To query objects in QuickBlox use the QBCustomObjects class:

NSMutableDictionary *getRequest = [NSMutableDictionary dictionary];
[getRequest setObject:@"5.5" forKey:@"rating[gt]"];
[getRequest setObject:@"5" forKey:@"limit"];
[getRequest setObject:[NSNumber numberWithBool:NO] forKey:@"documentary"];
[getRequest setObject:@"rating" forKey:@"sort_asc"];
 
[QBCustomObjects objectsWithClassName:@"Movie" extendedRequest:getRequest delegate:self];
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Get objects result
    if(result.success && [result isKindOfClass:QBCOCustomObjectPagedResult.class]){
       QBCOCustomObjectPagedResult *getObjectsResult = (QBCOCustomObjectPagedResult *)result;
       NSLog(@"Objects: %@, count: %d", getObjectsResult.objects, getObjectsResult.count);
    }else{
       NSLog(@"errors=%@", result.errors);
    }
}
QBCustomObjectRequestBuilder requestBuilder = new QBCustomObjectRequestBuilder();
requestBuilder.gt("rating", "5.5");
requestBuilder.setPagesLimit(5);
requestBuilder.eq("documentary", "false");
requestBuilder.sortAsc("rating");
 
QBCustomObjects.getObjects("Movie", requestBuilder, new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        if (result.isSuccess()) {
             QBCustomObjectLimitedResult coresult = (QBCustomObjectLimitedResult) result;
             ArrayList<QBCustomObject> co = coresult.getCustomObjects();
             Log.d("Records: ", co.toString());
         } else {
             Log.e("Errors",result.getErrors().toString());
         }
     }
});

Users

Use the QuickBlox Users Android and iOS samples to get more info.

Sign Up

To create a User with StackMob, you can extend the StackMobUser class, which is a specialized subclass of StackMobModel (for Android). For iOS - you can create users the same way you would create regular Core Data objects, except that the User entity NSManagedObject subclass will inherit from SMUserManagedObject, giving you secure methods to save your password:

NSManagedObjectContext *context = self.coreDataStore contextForCurrentThread];
User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
[user setUsername:@"Carl Atupem"];
[user setPassword:@"STACKMOBRULEZ123"];
[user setEmail:@"carl_atupem@aol.com"];
[user setPhone:@"617-666-1234"];
 
[context saveOnSuccess:^{
    // The user object saved successfully.
} onFailure:^(NSError *error) {
    // There was an error saving the user object.
}];
package com.stackmob.snapstack;
 
import com.stackmob.sdk.model.StackMobUser;
 
public class User extends StackMobUser {
 
    String email;
    String phone;
 
    public User(String username, String password, String email, String phone) {
        super(User.class, username, password);
    }
 
}
 
...
 
// Then you can call save:
User user = new User("Carl Atupem", "STACKMOBRULEZ123", "carl_atupem@aol.com", "617-666-1234");
user.login(new StackMobModelCallback() {
 
    @Override
    public void success() {
    }
 
    @Override
    public void failure(StackMobException e) {
    }
}

With QuickBlox just use QBUsers class:

QBUUser *user = [QBUUser user];      
user.login = @"Javck";
user.password = @"javckpassword";
user.facebookID = @"124343453463463";
user.twitterID = @"142345256";
user.fullName = @"Javck Bold";
user.email = @"Javck@mail.com";
user.phone = @"0947773823";
user.tags = [NSArray arrayWithObjects:@"man", @"travel", nil];
user.website = @"www.mysite.com";
 
[QBUsers signUp:user delegate:self];
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
-(void)completedWithResult:(Result*)result{
        // Create User result
	if(result.success && [result isKindOfClass:[QBUUserResult class]]){
            QBUUserResult *userResult = (QBUUserResult *)result;
	    NSLog(@"Registration was successful, user=%@", userResult.user);
	}else{
	    NSLog(@"errors=%@", result.errors);
	}	
}
final QBUser user = new QBUser("Javck", "javckpassword");
user.setFacebookId("100233453457767");
user.setTwitterId("182334635457");
user.setEmail("Javck@mail.com");
user.setFullName("Javck Bold");
user.setPhone("+18904567812");
StringifyArrayList<String> tags = new StringifyArrayList<String>();
tags.add("car");
tags.add("man");
user.setTags(tags);
user.setWebsite("www.mysite.com");
 
QBUsers.signUp(user, new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        if (result.isSuccess()) {
            QBUserResult qbUserResult = (QBUserResult) result;
            Log.d("Registration was successful","user: " + qbUserResult.getUser().toString());
        } else {
            Log.e("Errors",result.getErrors().toString()); 
        }
    }
});

Social login

Here's how StackMob's Facebook login looks:

[[SMClient defaultClient] loginWithFacebookToken:@"FACEBOOK_TOKEN" createUserIfNeeded:YES
  usernameForCreate:@"Carl Atupem" onSuccess:^(NSDictionary *result) {
      NSLog(@"User logged in through Facebook!");
} onFailure:^(NSError *error) {
      NSLog(@"Error logging in through Facebook: %@", error);
}];
// Passing true creates a user if needed
user.loginWithFacebook(facebookToken, true, "Carl Atupem", new StackMobOptions(), new StackMobModelCallback() {
    @Override
    public void success() {
    }
 
    @Override
    public void failure(StackMobException e) {
    }
});

Here is the same Facebook login with QuickBlox:

[QBUsers logInWithSocialProvider:@"facebook" accessToken:@"AAAGmLYiu1lcBADxROiXg4okE80FQO1dJHglsbNT3amxmABnmBmhN6ACbgDqNC3H4Y9GmZAdoSfPUkI9O7ZBJvKQCewNZAp3SoxKCNIMwQZDZD" accessTokenSecret:nil delegate:self];
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    if(result.success && [result isKindOfClass:[QBUUserLogInResult class]]){
        QBUUserLogInResult *loginResult = (QBUUserLogInResult *)result;
        NSLog(@"LogIn was successful, user=%@", loginResult.user);
    }else{
	NSLog(@"errors=%@", result.errors);
    }
}
String facebookAccessToken = "AAAEra8jNdnkBABYf3ZBSAz9dgLfyK7tQNttIoaZA1cC40niR6HVS0nYuufZB0ZCn66VJcISM8DO2bcbhEahm2nW01ZAZC1YwpZB7rds37xW0wZDZD";
 
QBUsers.signInUsingSocialProvider(QBProvider.FACEBOOK, facebookAccessToken, null, new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        if (result.isSuccess()) {
            QBUserResult qbUserResult = (QBUserResult) result;
            Log.d("LogIn was successful","user: " + qbUserResult.getUser().toString());
        } else {
            Log.e("Errors",result.getErrors().toString()); 
        }
    } 
});

Location

Use the QuickBlox Location Android and iOS samples to get more info.

Location points look like this in StackMob:

SMGeoPoint *point = [SMGeoPoint geoPointWithLatitude:40.0 longitude:-30.0];
StackMobGeoPoint point = new StackMobGeoPoint(40.0, -30.0);

With QuickBlox to create a check-in use QBLocation class:

QBLGeoData *geodata = [QBLGeoData geoData];
 
// place coordinates
geodata.latitude = 23.2344;
geodata.longitude = -12.23523;
geodata.status = @"I'am at QuickBlox house!";
 
[QBLocation createGeoData:geodata delegate:self];
QBLocation location = new QBLocation(23.41422, 12.436346, "I'm at PIzzeria";
QBLocations.createLocation(location, new QBCallbackImpl() {
    ...
});

Content storage

Use the QuickBlox Content Android and iOS samples to get more info.

StackMob allows for binary data to be attached to objects and saved to S3 seamlessly:

NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
 
// Convert the binary data to string to save on Amazon S3
NSString *picData = [SMBinaryDataConversion stringForBinaryData:imageData name:@"image.jpg" contentType:@"image/jpg"];
 
// Save to an existing User managed object, with string attributes `image` and `imageCaption`:
User *user = self.user;
[user setImage:picData];
[user setImageCaption:@"Start from the bottom, now we're here!!"];
byte[] image = // ... get the bytes of whatever you're uploading
Task myTask = new Task("Upload some files", new Date());
myTask.setPhoto(new StackMobFile("image/jpeg", "mypicture.jpg", image);
test.save(new StackMobModelCallback() {
    @Override
    public void success() {
        System.out.println(test.getPhoto().getS3Url());
    }
 
    @Override
    public void failure(StackMobException e) {
    }
});

With QuickBlox you can use the Content module to store any size files:

// your file - this is an image in our case
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"arrow.png"]);
 
[QBContent TUploadFile:imageData fileName:@"arrow.png" contentType:@"image/png" isPublic:YES delegate:self];
// isPublic:YES means that this file will be able to download any person on the internet using full link. 
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result*)result{
    // Upload file result
    if(result.success && [result isKindOfClass:[QBCFileUploadTaskResult class]]){
        // File uploaded, do something
 
        QBCBlob *uploadedFile  = ((QBCFileUploadTaskResult *)result).uploadedBlob;
 
        // File public url. Will be null if isPublic:NO in query 
        NSString *fileUrl = [uploadedFile publicUrl];
    }else{
        NSLog("errors=%@", result.errors);
    }
}
/ get file
int fileId = R.raw.sample_file;
InputStream is = context.getResources().openRawResource(fileId);
File file = FileHelper.getFileInputStream(is, "sample_file.txt", "myFile");
 
Boolean fileIsPublic = true;
 
QBRequestCanceler requestCanceler = QBContent.uploadFileTask(file, fileIsPublic, new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        if (result.isSuccess()) {
            // File uploaded, do something
 
            QBFileUploadTaskResult fileUploadTaskResultResult = (QBFileUploadTaskResult) result;
            QBFile qbFile = fileUploadTaskResultResult.getFile();
 
            // File public url. Will be null if fileIsPublic=false in query
            String publicUrl = qbFile.getPublicUrl();
 
         } else {
             Log.e("Errors",result.getErrors().toString());     
         }
     }
});

Push Notifications

Use QuickBlox Push Notifications Android and iOS samples to get more info

Here's how sending a push notification looks with StackMob:

NSMutableDictionary *pushMessage = [NSMutableDictionary dictionary];
NSArray *users = [NSArray arrayWithObject:@"Carl", @"Erick", @"Justin", nil];         
[pushMessage setValue:@"Hey, do you like Bon Jovi?" forKey:@"alert"];
[pushMessage setValue:@"ping.caf" forKey:@"sound"];
 
[self.pushClient sendMessage:pushMessage toUsers:users onSuccess:^{
    NSLog(@"Succesfully sent push message");
} onFailure:^(NSError *error) {
    NSLog(@"Error sending broadcast push message: %@", error);
}];
Map<String, String> payload = new HashMap<String, String>(); 
payload.put("payload", getPushPayload()); 
user.sendPush(payload, standardToastCallback);

QuickBlox's push notifications work similarly:

NSString *mesage = @"Hello man!";
NSMutableDictionary *payload = [NSMutableDictionary dictionary];
NSMutableDictionary *aps = [NSMutableDictionary dictionary];
[aps setObject:@"default" forKey:QBMPushMessageSoundKey];
[aps setObject:mesage forKey:QBMPushMessageAlertKey];
[payload setObject:aps forKey:QBMPushMessageApsKey];
 
QBMPushMessage *message = [[QBMPushMessage alloc] initWithPayload:payload];
 
// Send push to users with ids 292,300,1295
[QBMessages TSendPush:message toUsers:@"292,300,1395" delegate:self];
// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(53779);
userIds.add(960);
 
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
 
QBMessages.createEvent(event, ...);

Datastore migration guide

QuickBlox provides easy way to migrate your StackMob datastore schemas to QuickBlox. In QuickBlox world we call it Custom Objects. In order to start data migration it will be helpful to read Custom Objects documentation.

Let's start.

StackMob data export

Go to StackMob dashboard. On this page there are all your schemas. We have one custom schema here called Todo:

Stackmob export1.png

with next fields:

Stackmob export2.png

To export all records from schema Todo go to Data management, open Export Data tab, select format to export, email and click Export data button:

Stackmob export3.png

You'll receive an email with a link to your exported data when it's done.

QuickBlox data import

Go to QuickBlox admin panel, open Custom Objects module:

QuickBlox import1.jpeg

If you don't have an account or don't know how to create application - please follow 5 mins guide

In Custom Objects module click Add new class button, enter class name and add all fields:

QuickBlox import2.png

Click Create class button. You created a class with no records:

QuickBlox import3.png

To import data go to Import tab, choose Todo class, choose file to import (in our case it's todo.json) and click Import button:

QuickBlox import4.png

Your data will be processed and imported. Wait until status field will be complete in Jobs table.

Then back to List tab and check your data:

QuickBlox import5.png

What's next?

We have done it. This guide shows StackMob and QuickBlox SDKs similarity and explains how to migrate data from StackMob dashboard to QuickBlox custom objects.

What's next? Sign Up and start building your communication and data services on the QuickBlox platform. Use QuickBlox 5 mins guide to start!

Good luck!