Bridging between Swift and Objective-C in the Same Project

In this tutorial you will call objective-C from swift using bridging header.

Swift and Objective-C in the Same Project
Swift’s compatibility with Objective-C lets you create a project that contains files written in either language. You can use this feature, called mix and match, to write apps that have a mixed-language codebase. Using mix and match, you can implement part of your app’s functionality using the latest Swift features and seamlessly incorporate it back into your existing Objective-C codebase.

Mix and Match Overview
Objective-C and Swift files can coexist in a single project, whether the project was originally an Objective-C or Swift project. You can simply add a file of the other language directly to an existing project. This natural workflow makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

The process for working with mixed-language targets differs slightly depending on whether you’re writing an app or a framework. The general import model for working with both languages within the same target is depicted below and described in more detail in the following sections.

swift

swift

Importing Code from Within the Same App Target
If you’re writing a mixed-language app, you may need to access your Objective-C code from Swift and your Swift code from Objective-C. The process described in this section applies to non-framework targets.

Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Open any of your xcode projects (swift based) using xcode6. (Use this one, https://github.com/datomnurdin/SimpleiOSApp). Create new Objective-C Implementation (.m file) to your project. File > New > File.

xcode6 - new file

xcode6 – new file

Select iOS > Source > Objective-C File. Click Next.

xcode6 - Objective-C File

xcode6 – Objective-C File

Name it CustomObject. Click Next and Create.

xcode6 - new file

xcode6 – new file

When adding your .m file, you’ll likely be hit with a prompt that looks like this below and click Yes.

Objective-C bridging header

Objective-C bridging header

Your CustomObject.m and SimpleiOSApp-Bridging-Header.h have been created.

CustomObject.m and SimpleiOSApp-Bridging-Header.h

CustomObject.m and SimpleiOSApp-Bridging-Header.h

Add another .h file and name it CustomObject.hFile > New > File. Select iOS > Source > Header File. Click Next.

Header File

Header File

Name it CustomObject and click Create.

CustomObject.h

CustomObject.h

Your CustomObject.h just created.

CustomObject.h

CustomObject.h

Build your Objective-C Class

In CustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end

In CustomObject.m

#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"I love you iena!!");
}

@end

Now add Class to Bridging-Header. In YourProject-Bridging-Header.h (For this tutorial is SimpleiOSApp-Bridging-Header.h):

#import "CustomObject.h"

Then use your Object. In ViewController.swift after viewDidLoad() function.

var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello Iena"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

Then run your project. Check your console.

xcode6 console

xcode6 console

Output

Hello Iena
2014-12-30 15:10:16.760 SimpleiOSApp[2114:74245] I love you iena!!

AngularJs Ionic Mobile App Development Tutorial – Marketing App – Part 1

In this tutorial you will develop a marketing app for iOS and android with these features

  • Login (Facebook Login)
  • Edit profile
  • Create and view all campaign details
  • View reports

What you will be learn from this tutorial are

  • Setup development environment using certain IDE for iOS and android.
  • Preview your iOS and android hybrid app on actual device (smart phone).
  • Develop iOS and android hybrid app using client side language.
  • Create multi page application for iOS and android hybrid app.
  • Connect iOS and android hybrid app with server side language.

Download the required software packages.

Download and install Eclipse Juno SR2 and Xcode 6 (if you’re using Mac for mobile development).

Eclipse Juno SR2 – http://www.eclipse.org/downloads/packages/release/juno/sr2
Xcode 6 – https://developer.apple.com/xcode/downloads/

Setup ADT and Android SDK into your eclipse.

Then you need to setup cordova using NPM (node package manager).

ADT and Android SDK Setup

Don’t forget to install or update your machine with latest JDK 7. Download at http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html.

After you download, make sure you set the correct java path. If not, you can’t start your eclipse. You can download eclipse Juno http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/junosr2.

Then install it. After you install the tool that I tell you, make sure you install ADT (android development tools).

Go to Help and choose Install New Software.

eclipse - Install New Software

eclipse – Install New Software

Click Add button then popup box will appear. Enter ‘ADT’ in name textfield and ‘https://dl-ssl.google.com/android/eclipse/’ in location textfield.

eclipse - Install ADT

eclipse – Install ADT

Click Select All button and click Next.

eclipse - Install ADT

eclipse – Install ADT

Click Next.

eclipse - Install ADT

eclipse – Install ADT

Select I accept the terms of the license of agreement. Click Finish.

eclipse - Install ADT

eclipse – Install ADT

After finished setup ADT in your eclipse, download android SDK (http://developer.android.com/sdk/index.html#Other) and update latest android version or depends on your device for testing. After you install the android SDK, open android SDK , /android-sdk/tools. For this tutorial we will using latest android SDK, Android 5.0 aka Lolipop. Open your terminal/cmd, type android command and enter.

android terminal

android terminal

Select Android 5.0 and click Install 12 packages.

Android SDK Manager

Android SDK Manager

Select all packages, choose Accept License and click Install.

Android SDK Manager

Android SDK Manager

After that, install node.js (http://nodejs.org/) to use npm for package manager. If you not install node.js, you should not be able to invoke node or npm on your command line to install cordova apache. Then install cordova apache using terminal for Mac, command prompt for Windows.

Type this command to install cordova apache.

For Mac

sudo npm install -g cordova ionic

For Windows. If you can’t install, make sure you run the command prompt as administrator.

npm install -g cordova ionic
sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

After you finish install the cordova apache. You can start create your project using cordova command. Open your terminal/command prompt, type these command. You can ignore sudo if you using Windows.

ionic start com.revivalx.cordova.marketing
ionic create project

ionic create project

Open config.xml inside cordova project that you already created just now. Change id and name. Others are optional.

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.cordova.marketing" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>ToDo</name>
    <description>
        Marketing App.
    </description>
    <author email="mohammadnrdn@gmail.com" href="http://revivalx.com">
        Mohammad Nurdin bin Norazan
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

Go back to terminal and add platform for android/iOS. Type these command to add both platforms.

ionic platform add android
ionic platform add android

ionic platform add android

ionic platform add ios
ionic platform add ios

ionic platform add ios

Note, if you got some error message during add andorid platform, you can refer to this link

Common errors during developing hybrid android app– http://blog.revivalx.com/2014/11/02/common-errors-during-developing-android-hybrid-app/

Android part.

Go to eclipse and import android project. Click File and choose Import.

eclipse - import project

eclipse – import project

Choose Existing Android Code into Workspace and click Next.

eclipse - existing android code into workspace

eclipse – existing android code into workspace

Browse your android project and select all. Click Finish.

eclipse – import projects

eclipse – import projects

Make sure you already connect your mobile device (android phone) and enable USB debugging.

Enable USB debugging: http://www.phonearena.com/news/How-to-enable-USB-debugging-on-Android_id53909

Right click android project > Run As > Android Application.

Run As Android Application

Run As Android Application

Select your phone and click Ok.

Android Device Chooser

Android Device Chooser

If successful, your app shown like this.

cordova app preview on android

ionic app preview on android

iOS part.

Open your cordova project for iOS. Go to../com.revivalx.ionic.marketing/platforms/ios/com.revivalx.ionic.marketing.xcodeproj . Select iPhone6 simulator and click Play button.

xcode6

xcode6

If successful, your app shown like this.

ionic app preview on iOS

ionic app preview on iOS

I think thats all for

  • Setup development environment using certain IDE for iOS and android.
  • Preview your iOS and android hybrid app using emulator and actual device (smart phone).

Next tutorial we will develop iOS and android hybrid app using client side language.

Swift Tutorial: A Simple Login iOS App

In this tutorial you will develop a simple iOS app with login feature. User can login this app and the app will verify user credential. What you will be learn from this tutorial are

  • Setup development environment
  • Storyboards and interface builder
  • Creating views
  • Creating view controllers
  • Connecting view controllers with views
  • Calls JSON Web services
  • Navigate programmatically between views
  • Preview your app

What you need for this tutorial are

Getting started

Open your Xcode6. Since swift only supported in Xcode6, so we will using it. Choose Create a new Xcode project.

xcode6

Xcode6

Select Single View Application and click Next.

Choose a template for your new project

Choose a template for your new project

Enter your Product Name, Organization Name and Identifier. Leave it for Language, Devices and Use Core Data since we using swift, both devices (iphone and ipad) and store user credential in local database. Click Next. Then a popup will appear to let you create a new xcode project on your machine directory. Make sure tick Create Git Repository on My Mac because we can do versioning control. Then click Create.

Choose options for your new project

Choose options for your new project

Open your Main.storyboard.

Main.storyboard

Main.storyboard

Now we need to create another View Controller.

View Controller

View Controller

Select View Controller, drag and drop on storyboard. Now we have two View Controller on Main.Storyboard.

two View Controllers on Main.storyboard

two View Controllers on Main.storyboard

Now we need to create a view controller class for second view controller that we already created. Open File > New > File.

create a new view controller class

create a new view controller class

Select Cocoa Touch Class under iOS > Source. Click Next.

Cocoa Touch Class

Cocoa Touch Class

Name it as DashViewController. Click Next.

Choose options for your new file

Choose options for your new file

Click Create to save.

Choose new view controller class

Choose new view controller class

Remove all except override func viewDidLoad() .

import UIKit

class DashViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

Go back to Main.storyboard and open Document Outline. Now we need to connect second View Controller with DashViewController class. Open Identity Inspector and select DashViewController in Class selection field. Now you can close the Document Outline.

Connecting view controller with view

Connecting view controller with view

Create a login form like image below. The login form must has username textfield, password textfield and login button. Make sure you set autolayout for these three things (username textfield, password textfield and login button), so alignment will looks nice when it run inside the iphone and ipad. You can learn more details about the autolayout here, http://blog.revivalx.com/2014/10/22/swift-autolayout-tutorial/

Login Form in View Controller

Login Form in View Controller

Open Assistant Editor to start editing the code.

Assistant Editor

Assistant Editor

Remove all except override func viewDidLoad() .

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

}

Create outlets and action via Drag and Drop for each textfield and button. You can learn it from here, http://www.theappguruz.com/uncategorized/build-ios-outlet-action-via-drag-drop-method/. Make sure your end result will be like this.

ViewController class

ViewController class

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txtUsername: UITextField!

    @IBOutlet weak var txtPassword: UITextField!

    @IBAction func btnLogin(sender: AnyObject) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

}

For this tutorial, we will using REST API to request and response JSON data between the app and server. Call REST API using GET method like sample below

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txtUsername: UITextField!

    @IBOutlet weak var txtPassword: UITextField!

    @IBAction func btnLogin(sender: AnyObject) {

        var url : String = "http://demo.revivalx.com/todolist-api/login.php"
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: url)
        request.HTTPMethod = "GET"

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

            if (jsonResult != nil) {
                println(jsonResult)
            } else {
                // couldn't load JSON, look at error
            }

        })

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

}

 

Building HTML5 Games with ImpactJS – Part 1

In this tutorial you will develop simple html5 game using impactjs library. You will learning:

  • Setup Development Environment
  • Build a complete game with core logic, collision detection, and player and enemy behavior
  • Display and animate game artwork with sprite sheets
  • Add sound effects, background music and text
  • Create screens to display stats and in-game status
  • Prepare to publish by compile your game files into single file

Overview

Impact is a JavaScript game framework created by Dominic Szablewski. Impact takes advantage of the modern browser’s Canvas element in order to create high-performance 2D games on the Web and even mobile. One of the biggest advantages of using Impact is that it is easy to pick up, comes with very good code examples, has an active community, and has a very robust level editor called Weltmeister. The only barrier of entry is the licensing fee for the software, since it is not open source. After purchasing a license, you do get the full source code, the Weltmeister level editor, and free current major version updates (1.x). While there are other open source and free JavaScript game frameworks out there, Impact has an extra level of polish I haven’t seen with anything else so far. http://impactjs.com/

impactjs

impactjs

What do you need for this tutorial

Setting Up a New Impact Project

Before we can start this tutorial, you need to make sure you already purchased Impactjs library from link above and install all the software that I mention it before. To get started, copy the Impact project into your localhost. You should see the following files

Impact project files

Impact project files

You can rename impact folder to you own game project name. Mine is myNewGame. Here is a quick breakdown of everything in the folder:

  • index.html – This is the main .html file that runs your game.
  • lib – This is the core code for Impact and where you will store your own game-specific JS files. This also contains the source code for Weltmeister.
  • media – This is the assets directory, and where all game art and sound files will go.
  • tools – This directory contains .php scripts to minify your game’s JS files and make it harder for people to have access to the game’s source code. This is part of the license and is important so you don’t accidentally distribute the source code.
  • weltmeister.html – This is the level editor’s .html file.

Open your chrome and navigate to http://localhost:8888/myGame/index.html.

It Works!

It Works!

What is canvas? On the HTML canvas, you can draw all kinds of graphics, from simple lines, to complex graphic objects. The HTML <canvas> element (introduced in HTML5) is a container for canvas graphics. An HTML canvas is a rectangular area on an HTML page. Canvas has several methods for drawing paths, boxes, circles, text, and graphic images. http://www.w3schools.com/html/html5_canvas.asp

Modules

You can refer here for more details, http://impactjs.com/documentation/class-reference/ig-core.

Core Classes

Impact is made up of several core classes that revolve around the game framework and all the necessary systems such as rendering, maps, sounds, and more. All the classes are in the ig namespace, which is set up by the core class. http://impactjs.com/documentation/class-reference/ig-core

Level Editor

One of the best features of Impact is its level editor called Weltmeister. It is located in the libs/weltmeister folder inside the Impact project.

Weltmeister

Weltmeister

Next tutorial we will discuss about sprites and how to design the artwork for our HTML5 game. Stay tune.

Cordova/PhoneGap MissedCall Plugin for android

This MissedCall phonegap plugin can track for those missed call you easily. Internally, the plugin uses both the Native and the JavaScript implementations, it has sometimes been hard for the plugin to keep up with new versions of these SDKs, as well as new versions of Cordova.

The approach used in MissedCall is simple and lightweight, but it is definitely not perfect.

function missedCall(){
	cordova.exec(missedCallSuccess, missedCallFailure, "MissedCallPlugin", "missedCall", []);
}

Source Code

MissedCall plugin is available in this repository on GitHub.

Getting Started

To run the sample on your own app:

  • Install this phonegap plugin into your project.
  • Trigger missedCall() function.