Menu

Simple Badge Tutorial with Playbasis iOS SDK - Part II

Simple Badge Tutorial with Playbasis iOS SDK - Part II

We’re done with Part I on setting things up on Playbasis’s dashboard. Now it’s time to code!

Step 1. Download Playbasis iOS SDK

Go to http://dev.playbasis.com/download.php page to download the whole project as a zip file. Click on the IOS download button it and save a zip file to your computer.

Step 2. Create a new XCode project

Start XCode, and create a new Single-View application.

Then enter information as shown below.

Initially, your project’s file structure will be as follows.

If you want, just try to Run the application. It will show a launch screen for a short time, then show a blank white screen. This is normal, and indicated that you’re all set at this point.

Step 3. Integrate Playbasis SDK

Take the SDK package file you downloaded at the step 1. Unzip the file, and you will be seeing the following files inside.

Go back to your XCode. Click on the project on Project Navigator, then click on Build Phases. Expand “Link Binary With Libraries”, then click on “+” symbol then click on “Add Other …”. Finally, select “pblib.framework” in your downloaded folder.

You will get the result as follows.

Next we’re going to add .bundle file “pblibResource.bundle”. Click on project on Project Navigator, then click File->Add Files to … Then select “pblibResource.bundle” file.

Make sure that “Other Linker Flags” is set to “-ObjC”.

Now you’re ready to go, and code it out with Playbasis SDK.

Step 4. Hook up with APP_KEY and APP_SECRET

You have to encrypt the configuration file, and put it into the “pblibResource.bundle” yourself.

But we have already provided you “crypt” program to encrypt the file very easily with your specified key using in encryption and decryption process. The latter process will occur automatically and internally within SDK, so you don’t have to worry.

Firstly, create a text file. Let’s say we name the file as “keys-input.txt” with the content filled with your API_KEY, and API_SECRET as follows.

Now open terminal and go to your downloaded SDK folder, you will see “crypt” program.
Make sure it is executable by executing the following command.

chmod +x crypt

Next execute the following command to encrypt a file we’ve created.
Note that the usage is crypt -k <256-bit-keys> -i <input-file-path> -o <output-file-path>

crypt -k “abcdefghijklmnopqrstuvwxyz123456” -i keys-input.txt -o apikeys-config.txt

Make sure that output file is exactly with the name of “apikeys-config.txt” as the SDK will look for this file.

If you look at the content inside the output file, you will be seeing something like this.

Now go back to your XCode, click to expand “pblibResource.bundle”, then right click on “protectedResources” folder then select “Show in Finder”.

Then copy your output file to replace the file which is already there.
Now you’re done. Let’s move on to test it out.

If you’ve integrated SDK directly via source code

Using this approach will save you some times as you can configure API_KEY, and API_SECRET directly at the text file, and then let the project encrypts the file and finally copies it to the application’s bundle automatically.

Now let’s get to it.

Remember APP_KEY, and APP_SECRET we got back while we’re setting up in Playbasis’s dashboard, now we will use them in hooking up to our own application.

Go to “apikeys-config.txt” file under pblib project->protectedResources.

Enter information you got in Playbasis’s dashboard.

Next in ViewController.m file.
Add the following code at the top most of the file.

#import “Playbasis.h”

Also add the following code inside viewDidLoad() method.

[[Playbasis sharedPB] authWithBlock:^(PBAuth_Response *auth, NSURL *url, NSError *error) {
    if(!error)
    {
        NSLog(@"Authenticated app successfully %@", auth);
    }
}];

Then build and run the project, you should see the following output on console.

2015-03-02 18:10:12.074 PlaybasisTestApp[2199:505381] Reachability Flag Status: -R -----l- networkStatusForFlags
2015-03-02 18:10:12.077 PlaybasisTestApp[2199:505381] Network is reachable via WiFi
2015-03-02 18:10:12.347 PlaybasisTestApp[2199:505381] File didn\'t exist. Start fresh :)
2015-03-02 18:10:12.481 PlaybasisTestApp[2199:505381] Post request
2015-03-02 18:10:12.493 PlaybasisTestApp[2199:505381] date: 2015-03-02 11:10:12 +0000
2015-03-02 18:10:12.494 PlaybasisTestApp[2199:505381] dateStr: Mon, 02 Mar 2015 11:10:12 GMT
2015-03-02 18:10:12.495 PlaybasisTestApp[2199:505381] Sending request for https://api.pbapp.net/Auth?api_key=3383445682
2015-03-02 18:10:13.040 PlaybasisTestApp[2199:505381] token assigned: 2c585b6107ec4ba85727fbce9aa942f08c019f05
2015-03-02 18:10:13.041 PlaybasisTestApp[2199:505381] Authenticated app successfully Auth : {
        token : 2c585b6107ec4ba85727fbce9aa942f08c019f05
        date_expire : 2015-03-05 11:07:52 +0000
        }
2015-03-02 18:10:13.047 PlaybasisTestApp[2199:505381] called onApplicationDidFinishLaunching()
2015-03-02 18:10:13.415 PlaybasisTestApp[2199:505381] called onApplicationDidBecomeActive()

The bold text above is what we’re looking for. That means the application successfully authenticates itself with Playbasis system, and got back token to be used in our application.

Step 5. Create UI in Storyboard

Go to file “Main.storyboard” file

Then place UIButton, and UIImageView similar to what is shown below.

To achieve the above looks and feels, set “Size” to iPhone 5.5-inch, but it can be anything as you prefer.

We need to create constraints for both UI elements. This is required to make XCode positions UI correctly and gives us expected result at the end.

Like Button:

Hold down Control key and click on like button then move the mouse position to the empty area on the view. Then select “Center Horizontally In Container” as shown below.

Do the same but for the bottom

Badge ImageView:

Do the same as we did for Like button. But this time move the mouse position to the left and above edge of the iPhone screen to make it relative to the left, and above. Then finally set its “Mode” in “Attributes Inspector” on the right panel after clicking on itself to “Aspect Fit”. This will fit the image we’re going to be loading to fit in our allowed space.

Next we will make both of those UI elements that we’ve placed to be accessible in our source code.

Show an assistant editor by hitting Option + Cmd + Enter.

Open ViewController.h file.

Hold down Control button, and drag your button into ViewController.h file as shown below.

The popup will show asking which kind of Connection to form between a button and a source file (ViewController class). Select “Action” as Connection, and name it as “like” as we will do like action by touching it.

Do the same for UIImageView, but form it as a normal outlet. At last, you should get something like this.

Now go back to “ViewController.m”. We will send a request to let Playbasis platform knows that a user just “like”, and let it performs on behalf of us. In this case, we will be calling Engine API’s

Rule.

You can take a look at Playbasis’s API at http://doc.playbasis.com/pbapp/ . It’s exposed parameters are similar to what exposed in Playbasis iOS SDK.

As we’ve set up the rule, whenever we “like” for 2 consecutives of time within 20 seconds, then we will get the badge. At that point, we will show a badge image on screen.

Go to “ViewController.m” file.

Add

static NSString *kPlayerId = @"jon";

at the very top of the source file. This defines our user that will be using in this project.

Next go to like method, and add the following code inside it.

[[Playbasis sharedPB] ruleForPlayerAsync:kPlayerId action:@"like" withBlock:^(PBRule_Response *response, NSURL *url, NSError *error) {
    if(!error)
    {
    NSLog(@"%@", response);
     }
}, nil];

Run the project, and click on like button. For the first like, you will be seeing result on console similar to this one.

2015-03-03 08:15:30.485 PlaybasisTestApp[2311:534022] Rule Response: {
        events : Rule events : {}
        events-missions : (null)
        events-quests : (null)
        }

If you click on like button again (of course within 20 seconds as our rule tells so), you will be seeing result on console similar to this one.

2015-03-03 08:15:35.073 PlaybasisTestApp[2311:534022] Rule Response: {
        events : Rule events : {
            Rule's event : {
                    event_type : REWARD_RECEIVED
                    reward_type : badge
                    value : 1
                    reward_data : Badge's rule event data : {
                    badge_id : 54f42ac6be120b3a1e8b49b3
                    image : http://images.pbapp.net/data/1d3b8976ffdf5f020fb22ad4d87186fb.png
                    name : 2 Fast Like Badge
                    description : 
                    2 in consecutive fast like within 20 seconds delay will get this badge.
                    hint : 2 in consecutive fast like within 20 seconds delay will get this badge.
                    claim : NO
                    redeem : NO
                    }
            }
            events-missions : (null)
            events-quests : (null)
        }

That means, we just got a badge already! But we just didn’t show it just yet. Now it’s time to do so.

Step 6. Showing a Badge Reward

What we have right now, the application doesn’t answer much about good UX and visual feedback. We will do it in this step.

Remove out all code inside like method first at this point, we will modify it.

Every time, user clicks on like button, we will show a hud indicating that we’re doing something and please wait. Then when 2 consecutives likes are in placed, we will show a badge reward. Note also that every time we click like button, we will clear a badge image. That means we will start fresh every time we make a request.

Add the following code at the top inside like method.

// show loading hud
[[Playbasis sharedPB] showHUDFromView:self.view withText:@"Liking ..."];

This is utility method that Playbasis iOS SDK integrated into itself utilizing MBProgressHUD project. Developers can use it right away via our SDK without a need to further add it again.

Next add the following code.

// clear image every time we make a request
self.badgeImage.image = nil;
// make a request
[[Playbasis sharedPB] ruleForPlayerAsync:kPlayerId action:@"like" withBlock:^(PBRule_Response *response, NSURL *url, NSError *error) {
        if(!error)
        {
            // check for all events
            if(response.events != nil)
            {
                for(PBRuleEvent *event in response.events.list)
                {
                    // we got a badge!
                    if([event.rewardType isEqualToString:@"badge"])
                    {
                        // get a badge data
                        PBRuleEventBadgeRewardData *badgeData = event.rewardData;
                       
                        [UIImage startLoadingImageWithUrl:badgeData.image response:^(UIImage *image) {
                           
                            // update UI
                            dispatch_async(dispatch_get_main_queue(), ^{
                                // set image to show on UI
                                self.badgeImage.image = image;
                               
                                // hide HUD
                                [[Playbasis sharedPB] hideHUDFromView:self.view];
                            });
                        }];
                       
                        break;
                    }
                }
            }
           
            // hide hud
            dispatch_async(dispatch_get_main_queue(), ^{
                [[Playbasis sharedPB] hideHUDFromView:self.view];
            });
        }
    }, nil];

What it does is that it will firstly clear image, then check for all events that occurs after we’ve performed like action successfully. We then iterate through all those events one by one to see whether we got any badge reward back, if so then we load such a badge image via UIImage’s utility method and set it to our badge image on UI screen. Finally we hide a HUD.

Of course, for other rewards it might not be only for a badge. In general, you can check PBRuleEvent’s eventType property against “REWARD_RECEIVED” then you know you got reward back. But this sample we want to go for simple approach as much as possible to give you an idea on how easy to integrate the SDK to your own application in very minimum lines of code.

Now the result is this …

Note:

You may see that we didn’t log in user in this sample. It’s not required. But whenever you make a request ie. Calling ruleForPlayer: although that user didn’t exist then Playbasis system will automatically register that user with default information ie. e-mail. You will need to update user’s information later on as in the future you will need to do it to fully utilize functionality and features provided by Playbasis platform such as sending code via sms or email.