Apple Pay integration with Stripe tutorial

Why Apple Pay?

  • It’s an easy, secure and private way to pay within the app
  • One touch payment
  • No need to re enter payment or contact information
  • Private – cause credit card number are not exposed to the merchant, instead you are sent the device number and unique token that is only valid for that particular purchase.

Why use Apple Pay as developer?

  • You don’t need to handle credit card number
  • Higher conversion rate and faster checkout

Apple Pay  VS  In-App Purchase

  • Apple Pay is used for physical good’s & services where as In-App purchase is for in app content/functionality only
  • Developer is responsible of processing payment in Apple Pay where as Apple is responsible for processing payments in In-App purchase.

Prerequisites

iOS device (iPhone 6 or 6+, iPad Air 2, or iPad mini 3) running iOS 8.1 or later

Quick overview of how it works

  • You create a Merchant ID and matching certificate in Developer Portal
  • Your ID and certificate are used to encrypt the payment data
  • Display Payment sheet to user
  • User uses Touch ID to authorize transaction
  • Your app receives the payment token
  • This token is encrypted using your Merchant ID and certificate so only your application can decrypt it
  • Send token for processing using one of payment platforms like Stripe, Braintree, Shopify etc.

Create new Xcode Project

Screen Shot 2016-03-14 at 6.07.39 PM.png

Select “Single View Application” Template

Setup your app for ApplePay

Once project is created, login into your  http://developer.apple.com account. Go to Member Center and click on Certificates, Identifiers & Profiles\Identifiers\App IDs. Click on the + button to create a new App ID

Screen Shot 2016-03-14 at 6.13.23 PM

 

Screen Shot 2016-03-14 at 6.13.31 PM.png

Make sure that you select Explicit App ID is selected, as wildcard App IDs aren’t able to make payments with Apple Pay. Finally, check the Apple Pay checkbox under App Services, click Continue and then click Register to complete the creation of your new App ID.

Creating Merchant ID

Next click on Merchant ID under Identifiers pane. Then click on + or Continue to create new merchant ID for your app.

Screen Shot 2016-03-14 at 6.14.53 PM.png

Now that we have both Merchant ID and App ID we can head back to the Xcode Project

Under your project Capabilities turn on the Apple Pay option and add in your MerchantID

Screen Shot 2016-03-22 at 3.54.56 PM.png

The three items in the Steps section should all have checkmarks next to them to indicate that you’ve satisfied all of the requirements for using Apply Pay in your app.

In Main.Storyboard we are going to create textfield name, email and donation amount. We are also going to create a “Donate Again” button and Thank you message label, we are going to set there visibility hidden for now.

Screen Shot 2016-03-22 at 4.02.08 PM.pngScreen Shot 2016-03-22 at 4.02.30 PM.png

We are now going to create attached properties with these IBOutlets.We are also going to create UIButton property “payButton”which will be our ApplePay button later on. So our ViewController.h file now looks like this.

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *userEmail;
@property (weak, nonatomic) IBOutlet UITextField *donationAmount;
@property (weak, nonatomic) IBOutlet UILabel *thankYouMessage;
@property (weak, nonatomic) IBOutlet UIButton *donateAgainButton;
- (IBAction)donateAgainPressed:(id)sender;
@property (weak, nonatomic)  UIButton *payButton;
@end


The Apple Pay classes are part of PassKit, so you need that import to make things work.So lets add following right in our ViewController.h file.

@import PassKit;

Setting up Apple Pay button

Apple Pay is only available to a subset of iOS users. Before presenting the Apple Pay option to the current user, we are going to determine whether Apple Pay is available.

In ViewController.m file let put following

- (void)viewDidLoad {
 [super viewDidLoad];
 // Conditionally show Apple Pay button based on device availability
 if ([PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:@[PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex]]) {
 _payButton = [self applePayButton];
 
 //Set location of Apple Pay button
 _payButton.frame = CGRectMake(_donationAmount.frame.origin.x, _donationAmount.frame.origin.y + _donationAmount.frame.size.height + 22.0, _payButton.frame.size.width, _payButton.frame.size.height);
 [self.view addSubview:_payButton];
 }else{
 //Create alternate payment flow
 }
}
- (UIButton *)applePayButton {
 UIButton *button;
 if ([PKPaymentButton class]) { // Available in iOS 8.3+
 button = [PKPaymentButton buttonWithType:PKPaymentButtonTypePlain style:PKPaymentButtonStyleBlack];
 } else {
 // Create and return your own apple pay button
 }
 [button addTarget:self action:@selector(tappedApplePay) forControlEvents:UIControlEventTouchUpInside];
 return button;
}

In this example we are not handling older versions of iOS, but if your app targets older iOS versions  you will need to create your own button using Apple’s Human Interface Guidelines and assets.

If we run our App now we will see the ApplePay button appear on our screen, but it doesn’t do anything yet.

Simulator Screen Shot Mar 22, 2016, 4.42.51 PM

Now let’s make the Apple Pay button work.For that we are going to implement PKPaymentAuthorizationViewControllerDelegate. We implement this protocol to respond to user interaction with the view controller.

@interface ViewController : UIViewController<PKPaymentAuthorizationViewControllerDelegate>

Implementing Delegates to Handle Payment Requests

We are going to implements the two required methods of the delegate in ViewController.m file:

- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didAuthorizePayment:(PKPayment *)payment completion:(void (^)(PKPaymentAuthorizationStatus))completion {
  //We are assuming right now that payment was successfull.
 completion(PKPaymentAuthorizationStatusSuccess);
}

- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller {
 //we are going to make all fields blank after user is done paying or canceling payment
 _donationAmount.text = @"";
 _userEmail.text = @"";
 _userName.text = @"";
 
 [self dismissViewControllerAnimated:YES completion:nil];
}

Setting up PKPaymentRequest

PKPaymentRequest instance is responsible for displaying the Apple Pay payment sheet.We will fill in required PKPaymentRequest elements.

- (PKPaymentRequest *)paymentRequest:(NSString *)amount {
 PKPaymentRequest *paymentRequest = [[PKPaymentRequest alloc] init];
 paymentRequest.merchantIdentifier = @"merchant.com.xxxxxx";
 paymentRequest.supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkVisa, PKPaymentNetworkMasterCard];
 paymentRequest.merchantCapabilities = PKMerchantCapability3DS;
 paymentRequest.countryCode = @"US";
 paymentRequest.currencyCode = @"USD";
 paymentRequest.paymentSummaryItems =
 @[
 [PKPaymentSummaryItem summaryItemWithLabel:@"Donation" amount:[NSDecimalNumber decimalNumberWithString:amount]],
 ];
 return paymentRequest;
}

Presenting Payment Sheet

When user taps on your Apple Pay button, we are going to present a PKPaymentAuthorizationViewController to initiate Apple Pay:

-(void)tappedApplePay{
 if ([self checkFormValid]){
 PKPaymentRequest *paymentRequest = [self paymentRequest:_donationAmount.text];
 PKPaymentAuthorizationViewController *vc = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:paymentRequest];
 vc.delegate = self;
 [self presentViewController:vc animated:YES completion:nil];
 }else{
 //Showing Alert to user if all values are not filled
 UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Please fill in all details" message:@"" preferredStyle:UIAlertControllerStyleAlert];
 
 UIAlertAction* ok = [UIAlertAction
 actionWithTitle:@"OK"
 style:UIAlertActionStyleDefault
 handler:^(UIAlertAction * action)
 {
 [alert dismissViewControllerAnimated:YES completion:nil];
 
 }];
 
 [alert addAction:ok];

 [self presentViewController:alert animated:YES completion:nil];
 }
}

-(BOOL)checkFormValid{
 BOOL valid = false;
 //We are doing some basic validation so we don't have amount blank while showing the payment sheet
 if ([_userName.text isEqualToString:@""] || [_userEmail.text isEqualToString:@""]|| [_donationAmount.text isEqualToString:@""]) {
 valid = false;
 }else{
 valid = true;
 }
 return valid;
}
Now lets run the app again and see the Apple Pay button in action. Once you fill in all the details and tap Apple Pay you should see the payment sheet with the option to pay with “Pay with Passcode”, if you are running this on iPhone you will see “Pay with TouchID” option.
Simulator Screen Shot Mar 28, 2016, 9.50.13 PM
Now only thing left to implement Stripe processing for Apple Pay.
Installing Stripe iOS SDK using CocoaPods
Let’s use CocoaPods to setup Stripe iOS library.  If you haven’t set up Cocoapods before, follow there installation instructions here. Then, add pod 'Stripe' to your Podfile, and run pod install. Close your project and use the .xcworkspace file to open your project in Xcode, instead of the .xcodeproj file, from here on out.
Screen Shot 2016-03-14 at 9.42.42 PM.png
Setting up Stripe for Apple Pay
Login/Register into your Stripe account and head to Apple Pay section of Account Setting.
Click on “Create New Certificate” and a .certSigningRequest file will automatically download.
Screen Shot 2016-03-14 at 10.27.01 PM.png
Now let’s head back to Apple Developer account. Click on Merchant ID under Identifiers pane and then click on Merchant ID we created for this app and hit edit.
Screen Shot 2016-03-14 at 10.29.23 PM.png
Upload the certificate downloaded from Stripe and hit continue.
Screen Shot 2016-03-14 at 10.29.45 PM.png
You’ll see a success page, with an option to download your certificate. Download it. Return to the Apple Pay section in Stripe dashboard and upload this .cer file to Stripe.
Screen Shot 2016-03-14 at 10.30.04 PM.png
Now our Stripe account is ready to work with Apple Pay.
Stripe API Keys
Get you test publishable API key from “API Keys” section of Account Setting. We will be setting it up in AppDelegate file, so it set for entire life cycle of the app.

Import Stripe in your AppDelegate.m file and setup publishable API key in method “didFinishLaunchingWithOptions”.

#import <Stripe/Stripe.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 [Stripe setDefaultPublishableKey:@"pk_test_key"];
 return YES;
}
Now lets add code to process the payment into Stripe Tokens. You can charge these tokens later in your server-side code.
In ViewController.m file lets import Stripe Libraries first.
#import <Stripe/Stripe.h>
Now in let change our PKPaymentAuthorizationViewControllerDelegate methods to handle stripe processing.
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didAuthorizePayment:(PKPayment *)payment completion:(void (^)(PKPaymentAuthorizationStatus))completion {
 
 [self handlePaymentAuthorizationWithPayment:payment completion:completion];
 
}

- (void)handlePaymentAuthorizationWithPayment:(PKPayment *)payment completion:(void (^)(PKPaymentAuthorizationStatus))completion {
 [[STPAPIClient sharedClient] createTokenWithPayment:payment completion:^(STPToken *token, NSError *error) {
 if (error) {
 completion(PKPaymentAuthorizationStatusFailure);
 return;
 }
 [self createBackendChargeWithToken:token completion:completion];
 }];
}

- (void)createBackendChargeWithToken:(STPToken *)token completion:(void (^)(PKPaymentAuthorizationStatus))completion {
 //We are printing Stripe token here, you can charge the Credit Card using this token from your backend.
 NSLog(@"Stripe Token is %@",token);
 completion(PKPaymentAuthorizationStatusSuccess);
 //Displaying user Thank you message for payment.
 _thankYouMessage.hidden = false;
 _payButton.hidden = true;
 _donateAgainButton.hidden =false;
}
Last thing we are going to do is to implement “donateAgianPressed” method to allow user to pay again.
- (IBAction)donateAgainPressed:(id)sender {
 _payButton.hidden =false;
 _donateAgainButton.hidden= true;
 _thankYouMessage.hidden = true;
}
Lets run our app and see Apple pay in action
Simulator Screen Shot Mar 29, 2016, 3.29.50 PM
Simulator Screen Shot Mar 29, 2016, 3.29.51 PM
Simulator Screen Shot Mar 29, 2016, 3.29.55 PM
Here is the full source code for this tutorial.

Simple Sprite Kit game tutorial- Part2

In the first part of the series, we created the basics scrolling background and a flying spaceship.

iOS Simulator Screen shot Oct 28, 2013 10.51.25 PM

In this part we are going to:

  1. Adding Missile with which spaceship can collide with
  2. Show end of game screen when spaceship collides with missile and give replay option
We are gonna add method to display missile on the screen, add this method at the end on MyScene.m

-(void)addMissile
{
    //initalizing spaceship node
    SKSpriteNode *missile;
    missile = [SKSpriteNode spriteNodeWithImageNamed:@"red-missile.png"];
    [missile setScale:0.15];

    //Adding SpriteKit physicsBody for collision detection
    missile.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:missile.size];
    missile.physicsBody.categoryBitMask = obstacleCategory;
    missile.physicsBody.dynamic = YES;
    missile.physicsBody.contactTestBitMask = shipCategory;
    missile.physicsBody.collisionBitMask = 0;
    missile.physicsBody.usesPreciseCollisionDetection = YES;
    missile.name = @"missile";
    //selecting random y position for missile
    int r = arc4random() % 300;
    missile.position = CGPointMake(self.frame.size.width + 20,r);
    [self addChild:missile];
}
For explanation of each line, take a look at addShip method. Once you have added this method add [self addMissile] at the end of initWithSize method and run to code to see our missile is appearing on the screen.
iOS Simulator Screen shot Nov 13, 2013 2.28.34 PM
Now we want to move the missile on the screen, so our spaceship can dodge it.
Add another constant for saving missile’s velocity right after background velocity.We want the missile to move little bit faster than background.
static const float BG_VELOCITY = 100.0;
static const float OBJECT_VELOCITY = 160.0;

Now we are going to add method to move the missile, at the end on MyScene.m

- (void)moveObstacle
{
    NSArray *nodes = self.children;//1

    for(SKNode * node in nodes){
        if (![node.name  isEqual: @"bg"] && ![node.name  isEqual: @"ship"]) {
            SKSpriteNode *ob = (SKSpriteNode *) node;
            CGPoint obVelocity = CGPointMake(-OBJECT_VELOCITY, 0); //2
            CGPoint amtToMove = CGPointMultiplyScalar(obVelocity,_dt); //3

            ob.position = CGPointAdd(ob.position, amtToMove); //4
            if(ob.position.x < -100)
            {
                [ob removeFromParent]; //5
            }
        }
    }
}
Let’s go through the code line by line.
  1. We collect all child nodes of the scene.
  2. Set the velocity by which the node is going to move
  3. Set the amount by which node has to move
  4. Set new position of the node
  5. We remove any node which has scrolled off the screen.
We going to call this method in update method like we called moveBg method. So now our update method looks like

-(void)update:(CFTimeInterval)currentTime {

    if (_lastUpdateTime)
    {
        _dt = currentTime - _lastUpdateTime;
    }
    else
    {
        _dt = 0;
    }
    _lastUpdateTime = currentTime;

    [self moveBg];
    [self moveObstacle];
}
Now we want to add missiles randomly at different y axis, every one second.
We are going to add another property to manage when was last time a missile was added on the screen.
    NSTimeInterval _lastMissileAdded;
We are going to use our update method to keep track of lastMissileAdded time interval.
-(void)update:(CFTimeInterval)currentTime {

    if (_lastUpdateTime)
    {
        _dt = currentTime - _lastUpdateTime;
    }
    else
    {
        _dt = 0;
    }
    _lastUpdateTime = currentTime;

    if( currentTime - _lastMissileAdded > 1)
    {
        _lastMissileAdded = currentTime + 1;
            [self addMissile];
    }

    [self moveBg];
    [self moveObstacle];

}
Run the project and you should be seeing multiple missiles on the screen now.
iOS Simulator Screen shot Nov 13, 2013 4.35.14 PM
Now we need to end the game if spaceship collides with the missile. To do that we need to add these two methods at the end of  MyScene.m


- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & shipCategory) != 0 &&
        (secondBody.categoryBitMask & obstacleCategory) != 0)
    {
            [ship removeFromParent];
    }
}

Since we set the scene as the contactDelegate of the physics world earlier, this method will be called whenever two physics bodies collide

There are two parts to this method:

  1. This method passes you the two bodies that collide, but does not guarantee that they are passed in any particular order. So this bit of code just arranges them so they are sorted by their category bit masks so you can make some assumptions later.
  2. Finally, it checks to see if the two bodies that collide are the spaceship and missile, and if so calls the method you wrote earlier.
If you run the current code, you will see if the spaceship collides with missile it will disappear.
Now, let’s create a new scene and layer that will serve as your “End of game” indicator. Create a new file with the iOS\Cocoa Touch\Objective-C class template, name the class GameOverScene, make it a subclass of SKScene, and click Next and then Create.
Then replace GameOverLayer.m with the following code:

#import "GameOverScene.h"
#import "MyScene.h"

@implementation GameOverScene
-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        // 1
        self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

        // 2
        NSString * message;
        message = @"Game Over";
        // 3
        SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        label.text = message;
        label.fontSize = 40;
        label.fontColor = [SKColor blackColor];
        label.position = CGPointMake(self.size.width/2, self.size.height/2);
        [self addChild:label];

        //4
        NSString * retrymessage;
        retrymessage = @"Replay Game";
        SKLabelNode *retryButton = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        retryButton.text = retrymessage;
        retryButton.fontColor = [SKColor blackColor];
        retryButton.position = CGPointMake(self.size.width/2, 50);
        retryButton.name = @"retry";
        [self addChild:retryButton];

    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location]; //1

    if ([node.name isEqualToString:@"retry"]) { //2

        //3
        SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
        MyScene * scene = [MyScene sceneWithSize:self.view.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        [self.view presentScene:scene transition: reveal];

    }
}
@end

There are four parts to initWithSize method:

  1. Sets the background color to white, same as you did for the main scene.
  2. Sets the message to “Game Over”.
  3. Displays the label with Sprite Kit, choosing font and size.
  4. Creating another Sprite Kit label to represent our “Retry” button.
To track when user hit the replay button, we need touchesBegan method. This method is called when user touches anywhere on the screen. Let’s break down this method
  1. We track the node present at the location where user touched the screen.
  2. If the node touched name is equal to “retry”, then it means user has hit the replay button
  3. We transition back to MyScene to restart the game. You can pick from a variety of different animated transitions for how you want the scenes to display – we choose a flip transition here that takes 0.5 seconds.Then you create the scene you want to display, and use thepresentScene:transition: method on the self.view property.
Just one more thing to do before our game is ready to play.
In MyScene.m after removing the spaceship after collision we need to transition to GameOverScene. So replace didBeginContact with following code.

- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & shipCategory) != 0 &&
        (secondBody.categoryBitMask & obstacleCategory) != 0)
    {
        [ship removeFromParent];
        SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
        SKScene * gameOverScene = [[GameOverScene alloc] initWithSize:self.size];
        [self.view presentScene:gameOverScene transition: reveal];

    }
}

Run the game and you should see Game over screen if you collide with a missile.

iOS Simulator Screen shot Nov 13, 2013 9.22.06 PM

And that’s a wrap! Here is the full source code for this Sprite Kit tutorial.

I hope you enjoyed this tutorial and are inspired to make your own game.

Simple Sprite Kit game tutorial- Part1

In this tutorial we are gonna make  a basics 2D games with Sprite Kit. You can get the full source code of this tutorial on github.

iOS Simulator Screen shot Oct 28, 2013 10.51.25 PM

Getting Started

Start Xcode and select File\New\Project from the main menu. Select the iOS\Application\SpriteKit Game template and click Next.

spritekit_project copy

Enter your game name for Product Name, choose iPhone for devices and leave the Class Prefix blank and click Next

create-project copy

On Device Orientation deselect Portrait.
only-landscape copy
In XCode’s toolbar, select the iPhone (4-inch) Simulator and click Run
run
You will see a single label that says “Hello World!” and when you click anywhere on the screen, a rotating space ship will appear.
hello copy spaceship copy

SpriteKit Physics and Collision Detection

SpriteKit comes with Physics engine built-in. Which helps in simulating realistic movements and collision detection.

We are going to use SpriteKit physics engine to move our spaceship and detect the collision between spaceship and missile.

We are build our game in following steps

  1. Adding Main character of the game(spaceship) on the screen (Part1)
  2. Adding scrolling background (Part1)
  3. Adding Missile with which spaceship can collide with (Part2)
  4.  Show end of game screen when spaceship collides with missile and give replay option (Part2)
Before starting these steps download the art folder from here, and add it to your Xcode project.

Adding Main Character

Open MyScene.m and you will see the code for displaying rotating space ship. For now delete everything in MyScene.m and replace it by.


#import "MyScene.h"
@implementation MyScene{
    SKSpriteNode *ship;
    SKAction *actionMoveUp;
    SKAction *actionMoveDown;
    NSTimeInterval _lastUpdateTime;
    NSTimeInterval _dt;
    NSTimeInterval _lastMissileAdded;
}

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        self.backgroundColor = [SKColor whiteColor];        
        //Making self delegate of physics World
        self.physicsWorld.gravity = CGVectorMake(0,0);
        self.physicsWorld.contactDelegate = self;

    }
    return self;
}
@end

Let’s go over what this does line by line

Variables ship, actionMoveUp,actionMoveDown,_lastUpdateTime,_dt and _lastMissileAdded we will using later on in code.

initWithSize: is the method that gets called when scene is first created.

        self.backgroundColor = [SKColor whiteColor];        

We set the background color to white.

        self.physicsWorld.gravity = CGVectorMake(0,0);
        self.physicsWorld.contactDelegate = self;

These lines set up the physics world to have no gravity, and sets the scene as the delegate to be notified when two physics bodies collide.

Add these lines right after importing MyScene.h
        
#import "MyScene.h"

static const uint32_t shipCategory =  0x1 << 0;
static const uint32_t obstacleCategory =  0x1 << 1;

These will setup two categories we will need in a bit
Now we are going to add spaceship on the screen. Add this method after initWithSize method
 
-(void)addShip
{
        //initalizing spaceship node
        ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
        [ship setScale:0.5];
        ship.zRotation = - M_PI / 2;

        //Adding SpriteKit physicsBody for collision detection
        ship.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ship.size];
        ship.physicsBody.categoryBitMask = shipCategory;
        ship.physicsBody.dynamic = YES;
        ship.physicsBody.contactTestBitMask = obstacleCategory;
        ship.physicsBody.collisionBitMask = 0;
        ship.name = @"ship";
        ship.position = CGPointMake(120,160);

        [self addChild:ship];

        actionMoveUp = [SKAction moveByX:0 y:30 duration:.2];
        actionMoveDown = [SKAction moveByX:0 y:-30 duration:.2];
}

Edit initWithSize method and add [self addShip] after setting background color to white
        self.backgroundColor = [SKColor whiteColor];  
        [self addShip];
Lets go over addShip method step-by-step
        ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
        [ship setScale:0.5];
        ship.zRotation = - M_PI / 2;
This creates a new SpriteKit node with Spaceship image and reduces the size of the image half. After that we rotate this ship so it points in the right direction.

        ship.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ship.size]; //1
        ship.physicsBody.categoryBitMask = shipCategory; //2
        ship.physicsBody.dynamic = YES; //3
        ship.physicsBody.contactTestBitMask = obstacleCategory; //4
        ship.physicsBody.collisionBitMask = 0; //5
        ship.name = @"ship"; //6
        ship.position = CGPointMake(120,160); //7
       [self addChild:ship]; //8

        actionMoveUp = [SKAction moveByX:0 y:30 duration:.2]; //9
        actionMoveDown = [SKAction moveByX:0 y:-30 duration:.2]; //10
  1. We are creating a rectangle physics body for the ship which has same size as ship node.
  2. Sets the category bit mask to be the shipCategory you defined earlier.
  3. Setting dynamic YES means that physics engine will not control the movement of the ship
  4. contactTestBitMask means  what categories of objects this object should notify the contact listener when they intersect.
  5. On collision with missile we don’t want the ship to bounce off, so we set collisionBitMask as 0
  6. Naming ship node.
  7. Setting position of ship on screen.
  8. Adding ship as child node of the scene.
  9. Defining SKAction for moving ship up
  10. Defining SKAction for moving ship down
Before we move further we need to replace MyScene.h by following

#import <SpriteKit/SpriteKit.h>
@interface MyScene : SKScene <SKPhysicsContactDelegate>

@end
If you run the project now, it wont show the spaceship where we want it be on the screen. To fix the issue, remove all the methods from ViewController and replace it by following


- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];

    SKView * skView = (SKView *)self.view;

    if (!skView.scene) {
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;

        // Create and configure the scene.
        SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;

        // Present the scene.
        [skView presentScene:scene];
    }
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}

We are now creating the scene from viewWillLayoutSubviews method instead of viewDidLoad. When viewDidLoad is called it is not aware of the layout of changes, hence it will not set the bounds of the scene correctly
iOS Simulator Screen shot Oct 28, 2013 8.02.43 PM
Now we are going to add capability to move the ship on its y axis based on where you have touched on the screen. In MyScene.m add following method

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self.scene]; //1
    if(touchLocation.y >ship.position.y){ //2
        if(ship.position.y < 270){ //3             
            [ship runAction:actionMoveUp]; //4         
        }     
    }else{        
        if(ship.position.y > 50){ 
            [ship runAction:actionMoveDown]; //5
        }
    }
}
  1. When track the location of the touch on the screen
  2. If the location is higher than the ship’s location then we want to move the ship up.
  3. Setting offset from the edge so ship completely stays in bounds of the scene
  4. Calling actionMoveUp to move the ship up by 30 points
  5. Calling actionMoveDown when touch location is below ship current location

Scrolling Background

Add these static vector math methods and constants right after obstacleCategory

static const float BG_VELOCITY = 100.0; //Velocity with which our background is going to move

static inline CGPoint CGPointAdd(const CGPoint a, const CGPoint b)

{
    return CGPointMake(a.x + b.x, a.y + b.y);
}

static inline CGPoint CGPointMultiplyScalar(const CGPoint a, const CGFloat b)
{
    return CGPointMake(a.x * b, a.y * b);
}

To make endlessly scrolling background, make two background images instead of one and lay them side-by-side. Then, as you scroll both images from right to left, once one of the images goes off-screen, you simply put it back to the right.
Add this method in MyScene.m
-(void)initalizingScrollingBackground
{
    for (int i = 0; i < 2; i++) {
        SKSpriteNode *bg = [SKSpriteNode spriteNodeWithImageNamed:@"bg"];
        bg.position = CGPointMake(i * bg.size.width, 0);
        bg.anchorPoint = CGPointZero;
        bg.name = @"bg";
        [self addChild:bg];
    }

}
Call this method right after setting background color to white.
        self.backgroundColor = [SKColor whiteColor];
        [self initalizingScrollingBackground];
Next we will add method in MyScene.m to move the background
- (void)moveBg
{
    [self enumerateChildNodesWithName:@"bg" usingBlock: ^(SKNode *node, BOOL *stop)
     {
         SKSpriteNode * bg = (SKSpriteNode *) node;
         CGPoint bgVelocity = CGPointMake(-BG_VELOCITY, 0);
         CGPoint amtToMove = CGPointMultiplyScalar(bgVelocity,_dt);
         bg.position = CGPointAdd(bg.position, amtToMove);

         //Checks if bg node is completely scrolled of the screen, if yes then put it at the end of the other node
         if (bg.position.x <= -bg.size.width)
         {
             bg.position = CGPointMake(bg.position.x + bg.size.width*2,
                                       bg.position.y);
         }
     }];
}
This finds any child with the “bg” name and moves it to the left according to the velocity
Finally to scroll the background with every frame we are going add update method in MyScene.m
 -(void)update:(CFTimeInterval)currentTime {

    if (_lastUpdateTime)
    {
        _dt = currentTime - _lastUpdateTime;
    }
    else
    {
        _dt = 0;
    }
    _lastUpdateTime = currentTime;

    [self moveBg];
}

Run the project and you should have a scrolling background.
iOS Simulator Screen shot Oct 28, 2013 10.51.25 PM