IOS Tutorials

Our mission is to build quality, efficient and cutting edge software solutions for our clients while building strong, well-rounded careers for our employees.

12 October 2015 alan.monson@stgconsulting.com Comments Off on IOS Tutorials Mobile

Delegation on iOS

This tutorial is a simple basic idea to show the concept of delegation on iOS, using Objective-C.
Delegation is usually not something a beginner would use, so this tutorial would be targeting intermediate users, which also means it assumes you know your way around Xcode and Objective-c at a reasonable level.
Final result – So here’s what the final app looks like: 


The app has 2 views, first view and second view. The first view has a label and a button, and the second view has a textField and a button. When you push the button on the second view, the text inside the textField gets placed in the label of the first view.
Pretty simple, but its a great demo of how delegation works.
Let’ start by setting up the UI.

Setting up the UI

  • Create a new single view project in Xcode using storyboards, objective-c and for iPhone.
  • Delete the default ViewController class (so “ViewController.h” and “ViewController.m”).
  • In the storyboard, make the single ViewController you have be embedded in a navigation controller. Add a second ViewController on your storyboard. Your storyboard should now have 3 elements: 1 NavigationController and 2 ViewControllers. Also, the first ViewController should be linked to the navigationController.
  • In the first ViewController add 2 labels and 1 button.
  • In the second ViewController add 1 label, 1 textField and 1 button.
  • I changed the color in the background of each ViewController to make it more obvious in this demo.
  • Create a new push segue between the first view controller and the second view controller (not the buttons but the controllers themselves) and name it “segueSecondView”.
  • At this point your UI should look something like this:

Create the classes for the ViewControllers

Create 2 new classes: FirstViewController and SecondViewController, both being a subclass of UIViewController. In your storyboard, make your first view controller be of custom class FirstViewController and your second view controller be of custom class SecondViewController.
Link the IBActions and IBOutlets from the UI to the classes as normal.
Create the protocol
After all the initial setup has been done, its time to start with the actual delegation.
In the SecondViewController.h, we need to do 2 things:

    • Declare a protocol
  • Create a variable of the newly created protocol

Here’s what the code looks like. I will explain it below:

//
//  SecondViewController.h
//  Test_Delegate
//
//  Created by Eduardo Flores on 3/20/15.
//  Copyright (c) 2015 Eduardo Flores. All rights reserved.
//
#import <UIKit/UIKit.h>
// declare the delegate
@protocol SecondViewDelegate
(void) textFromSecondView🙁NSString *)text;
@end // end protocol
// Declare the created delegate into our class
@interface SecondViewController : UIViewController
// Original declaration in our header
@property (nonatomic, weak) id<SecondViewDelegate>  delegate;
@property (weak, nonatomic) IBOutlet UITextField *textField_enterSomeText;
(IBAction)button_sendTextBack🙁id)sender;
@end //end interface


The code above has 2 main sections: the protocol and the interface.

The protocol declares methods that whoever will use this protocol will have to implement. This is pretty much like interfaces in Java. Just declare what the “delegate” has to do, but don’t implement it.
The name of the protocol usually, by convention, uses the word “Delegate” and it usually has the name of the class where it is declared.

The interface should look very common to you, with the exception of this line
@property (nonatomic, weak) id<SecondViewDelegate> delegate;
In here we’re just declaring a varilable to the protocol created above so we can refer to it from another class.

Passing the data back using the new delegate
What we want to happen is to take the text that’s inside the textfield and pass it back to the FirstViewController, and this will happen when we push the button we created in the SecondViewController. After we pass the data back to the FirstViewController, we’re going to pop the view to return the UI to the FirstViewController.

So with that idea, code for the button in the SecondViewController.m looks like this:

(IBAction)button_sendTextBack🙁id)sender
{
   // Send the data to whatever class implements the delegate
   [self.delegate textFromSecondView:textField_enterSomeText.text];
   // pop the view controller
   [[self navigationController]popViewControllerAnimated:YES];
}


So that’s all we have to do to declare a delegate in out SecondViewController, and to send data back to whoever or whatever class decides to declare itself as a delegate for the SecondViewDelegate.
At this point we’re done with SecondViewController.h and SecondViewController.m 

Implementing the delegate
Now that we have a class declaring it has a delegate, it is time to have another class declaring itself as delegate of the SecondViewDelegate.

In the FirstViewController.h we need to import the SecondViewController.h and say our class implements the SecondViewDelegate.
Here’s what the FirstViewController.h looks like:

//
//  FIrstViewController.h
//  Test_Delegate
//
//  Created by Eduardo Flores on 3/20/15.
//  Copyright (c) 2015 Eduardo Flores. All rights reserved.
//
#import
#import “SecondViewController.h”
@interface FIrstViewController : UIViewController <SecondViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *label_receivedText;
(IBAction)button_startSecondView🙁id)sender;
@end


Now we have declared the FirstViewController class is a delegate of SecondViewDelegate, so what’s the logic in FirstViewController?

    1. We need to push our view from FirstViewController to SecondViewController 
    1. We need to get a reference to the SecondViewController
    1. We have to get a reference then to the “delegate” variable in the SecondViewController
    1. Since we’re a delegate of SecondViewDelegate, we need to implement all of the methods in SecondViewDelegate. This means we have to implement the “- (void)textFromSecondView: (NSString *)text” method
  1. And finally, we need to set the text in the label of the FirstViewController with whatever text is “coming” from the SecondViewDelegate. This won’t be visible or applied until we see the FirstViewController the second time, after we return from SecondViewController

Step 1.
We’re going to push to the SecondViewController when we push the 1 button in our FirstViewController, so the implementation of the button would look like this:

(IBAction)button_startSecondView🙁id)sender
{
   [self performSegueWithIdentifier:@“segueSecondView” sender:nil];
}


Steps 2 and 3.
Since we’re using storyboard we can take advantage of the “prepareForSegue” method. In here we get a reference to the SecondViewController and we declare the FirstViewController as the delegate of the SecondViewDelegate. This is what it looks like:

(void)prepareForSegue🙁UIStoryboardSegue *)segue sender🙁id)sender
{
   SecondViewController *svc = (SecondViewController *)[segue destinationViewController];
   svc.delegate = self;
}


Steps 4 and 5.
Since we’re now the delegate of SecondViewDelegate we need to implement the “- (void)textFromSecondView:(NSString *)text”method, and in here we’re going to set our label from the FirstViewController with the String coming from the delegate.
So it looks like this:

(void)textFromSecondView🙁NSString *)text
{
   label_receivedText.text = text;
}


So there you have it. The SecondViewController now takes some text and sends it to the FirstViewController through the SecondViewDelegate.

The complete source code of this demo can be found on github, right here.

In-App purchases on iOS

The purpose of this tutorial is to teach how to create an extremely simple and basic iOS application, but enabling it to purchase non-consumable items from iTunes using Apple’s in-app purchase system.
I have found a large number of tutorials online about this subject, but most of them use large or existing applications to show this subject, making it harder to understand.
This app is targeted for intermediate level programmers, but it is written in a way that even a beginner programmer can do it. 

What you need for this tutorial

    • A mac with Xcode
    • A physical iOS device (iPhone/iPad/iPod Touch)
    • A paid iOS developer account on developer.apple.com. You should also have access to create new apps, products and sandbox users in iTunesConnect (this is enabled by default with paid iOS developer accounts)
  • Basic understanding of Objective-C


The final result
Let’s begin by showing you what the app is going to do. Remember, this is a dummy app and the Level 2 doesn’t do anything. I will also be using an iPad for this demo, but will work on all iOS devices.

    • The app has a single view with 2 buttons and 1 label. The single label shows which items you have already purchased:
    • When you click on the “Buy level 2” item you will be prompt to login (with your sandbox account), and you will be asked to confirm your purchase:
    • The app will then display a “Thank you for your purchase” type of message, and the second button (“Go to level 2”) will be enabled:

That’s all. Super simple but it works to illustrate the point of in-app purchases.
So, let’s get started.

Setup iTunesConnect
Before start writing a single line of code, or even open Xcode, we will setup iTunesConnect first for our application. This tutorial was created on March 2015, so iTunesConnect might look different for whenever you read this. The concept should remain the same.

    • Go to “Users and Roles”
  • Then go to “Sandbox Testers” and create a new account

Note: creating the sandbox tester account turned out to be a lot more difficult than what it should be. iTunesConnect doesn’t seem to like to use your own email address or any email address that has already been used on iTunesConnect. My best luck was to use a new email address that was not associated or used to log into iCloud, so when the “confirm email address” came, I just logged into the iCloud page with the password created for the Sandbox tester.

After the sandbox tester is created and the account has been verified, you need to log into your physical iOS device with this sandbox login you created. You need to do this in the “Settings -> iTunes & App Store” section of the iOS device.

Start creating the app on Xcode
While we still need to create the app and in-app purchase items in iTunesConnect, begin the creation of the app on Xcode, and running it on a device, helps to get the bundle id setup automatically on iTunesConnect.

    • Start Xcode
  • Create a new single view project

What really matters here in this view is the “bundle identifier.” You can modify it later if you want to, but for this demo we will just use something generic that should be available.

Note: iTunesConnect does not like dashes, so avoid them if you can.

Save the app and you will now have a “clean” (only boiler plate code) new project.
We will leave this code “as-is” for now, and we will continue setting up things on iTunesConnect and the iOS developer portal with the information we used on Xcode for our application.

Create the Bundle ID
The first thing we need to do for our application to  be added in iTunesConnect is create the application’s bundle id in the developer portal. So:

    • To the “Certificates, Identifiers & Profiles” section on the right
  • Under iOS, select “Identifiers”

At this point, you should be looking at something like this:


On the top right corner, click on the “+” button to create a new iOS app ID.
The name is what iTunesConnect will display, and the App ID Prefix is what Apple assigned for your Team ID. What really matters here is what you enter for App ID Suffix.
You could select a wildcard option, but in my experience that makes things get messy once you have multiple apps.

Select “Explicit App ID” and enter the bundle ID, created in Xcode as bundle identifier, exactly the same way it was entered in Xcode.


Scroll down and make sure In-App purchase is selected (it is by default at this time), and click on Continue. Review the information and click on Submit.

Create the App in iTunesConnect
With the bundle ID created, we are done with the developer portal (so you can close it) and we will be going back to iTunesConnect.

    • Go to “My Apps”
  • Click on the “+” sign on the top left, and create a new iOS app

In the next window, we will enter the name of the app, a language, the new Bundle ID we just created, the version of the app and a fake SKU. For real applications you might want to get a better SKU.

Note: iTunesConnect will treat this as a real app that you intend to release on the App Store. Because of this iTunesConnect will actually check to see if the bundle id is valid and if the name has been taken. If the name has been already taken, just change the name of the app to something else.

Since we’re not going to submit this app to the App Store, we won’t worry about screenshots, description, keyword or anything like that.

Setup your In-App products
Still not a single line of code!
In iTunesConnect, under your app go to “In-App purchases” and “Create a new” in-app purchase (note how I had to change the name of my app since DemoInApp was already taken)

 

Word on the street is that “Non-Consumable” is the most popular type of in-app purchase, since that’s what the cool kids use, we will use it as well.


Once we select the Non-Consumable type, we need to enter some information for our in-app product.

    • Reference name: Something internal that only you will see. Could be anything
    • Product ID: this is how we will refer to our in-app product from our code. Make it something relevant to your app, like adding the bundle prefix and the reference name
  • Price Tier: Could be anything, but selected Free since this is just a demo
    • Language: You are required to enter at least 1 language.
    • Display name and description: These will be a localized name and description of your in-app product and it will be visible to the end-user so make something appropriate.
  • Hosting with Apple: No. We’re not uploading content to apple at this time as the purpose of this simple demo is to enable things that already exist within the app but are hidden or disabled.


Save your in-app purchase product, and you should have something like this:


We are now finally and officially done with iTunesConnect, although we will need the “Product ID” to be called from our code.
Let’s move to Xcode now!

Create the UI for the application
The UI will be super simple. 2 buttons and 1 label. Organize them anywhere you want.

    • Button_buyLevel2: This button is what triggers the purchase of the in-app purchase. This button is visible and enabled
    • Button_goToLevel2: This button uses the in-app purchase. In practice this button will open a new window or access the new material the user just purchased. This button is hidden and disabled until the level 2 gets purchased.
  • Label_status: This is just a status line to tell you if the level 2 has been purchased

Notice how the Button_goToLevel2 is declared as both an IBAction and an IBOutlet. The reason for this is because we want to reference the Button_goToLevel2 and be able to hide it and disable it at runtime.

With the UI done, it’s time to setup the library we will use, and the code we will write.

Add StoreKit to the application
The application will use an Apple provided library called StoreKit to handle all in-app related transactions. You can add the StoreKit as part of the Capabilities of the app, or manually.
I will add it manually.

    • Select your application project in the Navigator
    • Go to “Build Phases”
    • Expand “Link Binary with Libraries”
    • Click the “+” to add a library
  • Select “StoreKit.framework” and add it


Congratulations. You just added StoreKit to your application.
Now it’s time to finally write some code!

Write the code for in-app purchases
When we created the project in Xcode, Xcode generated several files for us. We’re only going to work with 2 files. ViewController.h and ViewController.m.

In the header file (ViewController.h) we need to:

    • Import the StoreKit framework we just linked
    • Declare that our code will implement the SKPaymentTransactionObserver and the SKProductRequestDelegate delegates
    • Create a variable for the SKPaymentQueue
  • Create a variable for the SKProduct we will purchase

After this, your ViewController.h file should look like this:

//
//  ViewController.h
//  DemoInApp
//
//  Created by Eduardo Flores on 3/19/15.
//  Copyright (c) 2015 Eduardo Flores. All rights reserved.
//
#import
#import
@interface ViewController : UIViewController <SKPaymentTransactionObserver, SKProductsRequestDelegate>
{
   SKPaymentQueue *defaultQueue;
   SKProduct *product;
}
@property (weak, nonatomic) IBOutlet UILabel *Label_status;
@property (weak, nonatomic) IBOutlet UIButton *Button_goToLevel2;
(IBAction)Button_buyLevel2🙁id)sender;
(IBAction)Button_goToLevel2🙁id)sender;
@end


We’re done with our header file. We will now work on our implementation file (ViewController.m)
The first thing I always like to do is synthesize the IBOutlets I have. This is no longer necessary, but I still prefer this method over the self.variable option. 

In viewDidLoad, we will:

    • Initialize the SKPaymentQueue variable
    • Make the notify the defaultQueue that we will be the observer for transactions
    • Disable and hide the “Go to level 2” button since it hasn’t been purchased yet 
  • Call our method “getProductInfo” which will be created in a minute.

Our viewDidLoad looks like this now:

(void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    defaultQueue = [SKPaymentQueue defaultQueue];
    [defaultQueue addTransactionObserver:self];
    Button_goToLevel2.enabled = NO;
    Button_goToLevel2.hidden = YES;
    [self getProductInfo];
}


We will then create our “getProductInfo” method.
This method first checks if the application’s SKPaymentQueue is able to make payments. If it is, it creates a product ID with an NSSet of 1 single object using the Product ID we created in iTunesConnect for the in-app purchase product.
After that it creates a request, makes the delegate of the request look at this class for callbacks, and starts the request.
Our getInfoProduct method would then look like this:

(void) getProductInfo
{
   if ([SKPaymentQueue canMakePayments])
   {
       // This object comes from iTunesConnect
       // This is the in-app purchase item created
       NSSet *productID = [NSSet setWithObject:@“com.eduardoflores.level2”];   // From iTunesConnect in-app product
       SKProductsRequest *request = [[SKProductsRequest alloc]initWithProductIdentifiers:productID];
       request.delegate = self;
       [request start];
   }
}

Since we’re the delegate for the StoreKit transactionObserver and productRequest, we need to implement 2 methods to get the information from the StoreKit.
These methods are “paymentQueue:updatedTransactions” and “productsRequest:didReceiveResponse”

Here’s what the “paymentQueue:updatedTransactions” would look like:

(void)paymentQueue🙁SKPaymentQueue *)queue updatedTransactions🙁NSArray *)transactions
{
   for (SKPaymentTransaction *transaction in transactions)
   {
       switch (transaction.transactionState)
       {
           case SKPaymentTransactionStatePurchased:
               [self openLevel2];
               [defaultQueue finishTransaction:transaction];
               break;
           case SKPaymentTransactionStateFailed:
               [defaultQueue finishTransaction:transaction];
               break;
           case SKPaymentTransactionStateRestored:
               [defaultQueue restoreCompletedTransactions];
               break;
           default:
               break;
       }
   }
}


In here the paymentQueue:updatedTransactions we’re looping for a the transactions we’re getting from the paymentQueue. For each transaction we’re doing a switch based on the state of the transaction. If the SKPaymentTransactionState is “Purchased” we will then call a new method (which we will create in a minute) to open or enable the level 2 that has been purchased, and finish the transaction. If the transaction failed, finish the transaction. And finally, if the transaction was restored, let the queue restore the completed transactions.

Now here’s the “productsRequest:didReceiveResponse”:

(void)productsRequest🙁SKProductsRequest *)request didReceiveResponse🙁SKProductsResponse *)response
{
   NSArray *products = response.products;
   if ([products count] != 0)
   {
       product = [products objectAtIndex:0];
       NSLog(@“product Title = %@”, product.localizedTitle);
       NSLog(@“product Description = %@”, product.localizedDescription);
       Label_status.text = [NSString stringWithFormat:@“%@\n%@”, product.localizedTitle, product.localizedDescription];
   }
}


This one is super simple, and gets called at startup and gets all of the products that exist in our in-app inventory in iTunesConnect.
The delegate receives an array of responses, which we then call it products for simplicity.
For each product, we get the localized name and localized description which we added manually in iTunesConnect (remember, something appropriate in English only for now). Then we set these elements in the label to display it to the user, and in this case I’m also outputting them to the log just for fun.

There’s one more method mentioned in this tutorial, which is to open the level 2. In my case, all this method does is enable the button to use the level 2 and make it visible, like this:

(void) openLevel2
{
   NSLog(@“in openLevel2”);
   Button_goToLevel2.enabled = YES;
   Button_goToLevel2.hidden = NO;
}

Finally, pushing the “buy level 2” button triggers the purchase:
(IBAction)Button_buyLevel2🙁id)sender
{
   NSLog(@“in button_buyLevel2” );
   if (product)
   {
       SKPayment *payment = [SKPayment paymentWithProduct:product];
       [defaultQueue addPayment:payment];
   }
   else
       NSLog(@“Can’t handle payment. Product is null”);
}


I hope this tutorial helps! Below are some resources about about app development:

History of App Development

Mobile Development at Software Technology Group

Lastly, the source code for this project can be found here: Source Code

Tags: