Category Archives: iOS

iOS

There are lot of server side swift frameworks. The popular frameworks on GitHub are Perfect, Vapor, Kitura.

We will Create a small todo app using Postgres database, Will see how to implement simple routes and basic CRUD operations using Vapor framework.

Vapor :

This is the second most popular framework on GitHub for swift. Vapor provides best documentation and it build in swift3. And it will be a great staring point to start server side swift.  Vapor had all the packages that needed by an app and it has a very supporting community.

Reasons to use vapor :

  • Vapor uses web sockets to make real-time connections.
  • JSON Serialisation
  • Ability to create Controllers and Models.
  • Extensible, It uses Middlewares to add any parameters to HTTP requests. and we can add more functionalities
  • Expressive, The static type system allows you to write less and do more

Before getting started we need have these things

  1. Mac running on latest Os(Mac OS 10.12, Sierra)
  2. Xcode 8 or above
  3. Basic understand of swift language and iOS SDk

Getting started

Install Xcode : Install Xcode from App store

Install Vapor :

  • Compatibility Check : To check that your environment is compatible run the following script in terminal

  • If you get the green check mark, then you are all set to install vapor
  • Install vapor toolbox : Run the following command to install Vapor

    it might take a while. and finally we will get the message Vapor Toolbox v1.0.5-4-gd20c424 Installed

  • To check Vapor is working, just type the vapor command in your terminal and it will display like this                                                                          

Install Postgres : The easiest way to install Postgres is through Homebrew. If homebrew is not installed, download it from the link. Install Postgres using this command

Type the following command, to ensure that you have downloaded postgres

 

Starting a new vapor project :

We a building a simple todo app which can add, update and delete a todo. We will give api’s to do basic crud operations. Open terminal, And Cd to the directory of your choice and type the command.

This will create a new Todo Project

The directory will look like this

vapor creates a the Package.swift, here we can add any dependencies for the project. Then in the App folder, we can see main.swift, Controllers and Models.

The main.swift file is our main app file, where we can initialise and run the server

The resources folder contains the views, which contains and html and template files.

We can easily create Xcode project using vapor toolbox. Go to project directory type the command

This command will fetch the dependencies for the project and will take some time. After fetching all the dependencies it will ask you to open project in Xcode, type y and enter to open the project in Xcode

In Xcode project navigate to Source/App/Main.swift

We can see the code like this

This main.swift file imports the Vapor framework, and initiates the Droplet

Droplet, is a service that have access to Vapor functionalities. It is backbone of our server and it responsible for running server . So we import the vapor in main.swift and created an  intense of droplet.

The droplet will handle many properties, get the documentation from here 

Create a route: Now  create a route, a get request which returns the list of todos and finally run the drop.

Now run the Xcode project, make sure that you have selected app schema.

Run the application from Xcode to get the app running on localhost on port 8080. After Successfully building and running the app in Xcode. you can see  Server ‘default’ starting at 0.0.0.0:8080 in logs 

Now open the browser or post man and navigate to  http://localhost:8080/todos, we can see the list of todo’s

Create a Todo model :

Its good to have a Todo model, to avoid hard coding values. Vapor is providing model protocol, this will help us to convert models to JSON easily

vapor framework includes Fluent framework, which is ORM tool for swift that will work with different databases.

Cerate a file Todo.swift

The first property we will set is Id, this property will contain the identifier when model is fetched from DB, if it is nil it will set after when we save to DB.

Node Initializable :

we need to create a model from persistence data, model uses NodeInitializable to archive this data.

Node Representable :

NodeRepresentable will help us to save it back to database

Preparation :

We need to create a table for our Todo class, we will crate table using this prepare method. here we have created the todos Table .

Revert : 

this is the reversion of prepare method, this will be run using this command

Here it will delete the table todos.

Now we have seen how to create a route and model. Lets connect to Postgres database to create more routes

Setting up Postgres:

  • add the postgres provider url to Package.swift file

  •  
  • Regenerate Xcode project to download the postgres dependencies
  • Import the VaporPostgreSQL in main.swift file,
  • Append the Todo.self to drop preparation so that we can use model with Database
  • Then add provider to droplet so that database is available

     
  • Create a configuration file for Postgres, create the following file: Config/secrets/postgresql.json and update the file with these values, use your own username for  “user”
  • Creating Postgres Database, Run the Postgres server locally by using this command

    • Open another terminal and Create the database using this command
    • Type psql <Table name> command to get Postgres command line interface. Now we can check out routes by using postman. and plsql commands

Now we will create routes, which will perform the CRUD operations

AddTodo Route:

Now we are creating Add todo route using Postgres for adding todo and saving it to DB

In this route, we have created a new instance of todo from request (req.json), which is passed from post request.

Save that created instance using save() command.

This is post route is expecting body like this

GetTodo By ID Route :

Here, Int.self 2nd argument in the path so the url will be todo/1, so that we can send parameters in route.

We are using Fluent, So We can Easily use find(_:) , to get the instance of model

UpdateTodo By ID Route:

This is the route to update todo by using its Id. Here we will get id by Int.self and request parameters. We are getting the instance by using ID, and updating values in it and saving back to DB.

Delete Todo Route :

Here we are finding the model by using id and deleting it from DB.

Conclusion :

In this tutorial we covered, how to install vapor, Xcode, Postgres and Created API’s For Simple CRUD operations.  This server side swift is new technology and actively being developed by IBM, perfect an vapor teams.

This post will help to getting started with server side swift with Vapor.

Push notifications notifies user about messages or events when user is not using the application. Push notifications is a great way reach the users and perform simple tasks.

iOS supports two type of notifications :

1) Local Notifications : Which can be registered and schedule by app it self
2) Push (Remote) Notifications : Which can be schedule by another server not by the app. Mostly we will use web servers which can be send messages to multiple devices simultaneously .

Every notification sent by the provider(server) will follow path like
Provider —> APN Server —> Registered devices

There are two types of push notifications

1)Sandbox: Can be used in development stage
2)Production(Live) :  We Can use in production stage

What a push notification can do :

1) Display a short message
2) Play a sound
3) Set a badge number on app icon
4) Allowing app to do background tasks

What we need to test iOS Push notifications:

1) An iOS Device : iPhone/iPad (Push notifications won’t work in simulator )
2) An Apple developer program : To configure push notification, we need push notification certificate for that app id, Which requires a paid membership program
3) A Server : A web server which can be act as a provider

Configure app for push notifications : 

1) Create Xcode Project .

2) Edit bundle identifier for app
App Settings —> General

add_bundleid

3) Enable push notifications services in app
App Settings —> Capabilities

Enable_Push_Services

 Register  device for push notifications:

Open AppDeleagte.swift,  In application(_:didFinishLaunchingWithOptions) add this code

Add delegate methods to handle push notifications

This method will give the device token after successful registration with APN Server, Which we can send to web server(provider)

If device registration fails then we will receive error in this delegate method

print(“Notification Error :: \(error)”) }

After receiving push notification from APNS, we will get payload information in this delegate method.

Configure push notification certificates (in apple developer account):

  • Register App
    1. Sign in to https://developer.apple.com
    2. Goto Certificates, identifiers & profiles —> Identifiers —> App IDs —> Add new appadd_appID
    3. Give app name, Bundle identifier, enable push notifications in App services and then continueEnable_pushNotifications
    4. Make sure that  Push notifications should be configurable.push_services_configarableif any issues occurs we can edit the app id .
  •  Generate SSL certificate 
    1. Edit the app id, then we can see push notifications should be configurable
    2. In development SSL certificate Click on Create certificate. And follow the steps to create CSR filepush_configarablecreate_csr_popup
    3. Steps To Create CSR
      • Launch key chain on your mac
      • Select the menu item Keychain access —> certificate assistance —> request a certificate from certificate authoritycreate_csr
      • Enter your email address and name, Select “Save to disk” and then continue to download .csr_details
    4. Upload that CSR file to create a certificateupload_csr
    5. download the generated certificate (aps_development.cer) and run it. It will open in key chain and paired with a private keyDownload_cer
    6. In member center we can check development notifications are enabledenabled_devloper_notifications

 

Generate PEM and PFX file from certificate:

  1. Generate P12 file:Right Click on the  downloaded certificate and choose export. Save it as “Personal information Exchange(p12)” file. It will prompt for password for better security give a password and save it.Create_p12
  2. Generate private key:In terminal execute this command
  3. Generate pem file:
  4. Generate pfx file:

    These files will be used by the provider (Web server) to send the notifications to device

     

Create a Provisioning Profile:

  •  Goto Certificates, identifiers & profiles —> Provisioning Profile  —> All —> Add newprovision_create
    • Select type of provisioning profile and App id to create provisioning profile.
    • Go to Xcode –> Preferences –> Sign in to apple id –> download provisioning profilesdevloper_sign_in
    • Add this Provisioning Profile to your Code signing in XcodeApp Settings —> Build Settings —> Code Signing —> Provisioning Profileadd_profile_to_Xcode

Run the Application then we can see a prompt dialog, which is asking for permissions to send push notifications

sample_App

Send Push Notification:

For Sending push notification we need a back end server, which can communicate to APNS Server and sends notification to particular device

TEST Connection

Execute the following command in terminal

If everything is going good, it will ask for parse phase, enter parse phase. If the connection is successful it will ask for some input characters. Enter some characters and press enter to close connection

What is Charles Proxy?

– Usually we (QA) are asked to add the API request and response to the Bug/Jira that we raise during testing cycles. This is where Charles Proxy comes into picture. Charles Proxy is a tool mainly used to monitor the HTTP and SSL/HTTPS traffic between the web browser/client and the server. In simple words, Charles is used to view the API ‘Request’ sent to the server and ‘Response’ received from the server.

Configuring Charles Proxy :

Before we start using Charles, lets see how we can configure it. Below are the settings that need to be done in order to use Charles Proxy.

Settings to be Done on Laptop:

1- Ensure that the Laptop is connected to Wifi.
2- Download and install latest version of Charles Proxy from Here.
3- Open Charles Proxy. Purchase and add a license under ‘Help’.
4- Go to Proxy > Proxy Settings.
5- In ‘Proxies’ tab, under HTTP Proxy enter the port number as 8888.

Settings to be done on Mobile:

1- Find the IP associated with the Wi-Fi network to which your system is connected to.
2- Your mobile device should be connected to the same Wi-Fi network your Laptop is connected to.

For iOS Devices:

  1. Under the settings tap on Wi-Fi.                                                                                                            1
  2. Tap on the “i” icon beside the Wi-Fi network you are connected to.                                               2
  3. Under the HTTP Proxy section tap ‘Manual’ and enter the IP address of your Mac/Windows Machine running Charles Proxy and the port Charles Proxy is running on.                                  4 3
  4. Open Safari on your mobile device and visit a website. The following should pop up on your mac. Click Allow.                                                                                                                                       5
  5. You should now be able to sniff HTTP traffic. Visit the host on mobile safari. You may get a security warning due to the self signed certificate Charles will present . You want to add an exception for that host.
  6. Open the mobile app and you should be able to observe HTTPs traffic. The mobile iOS/Android client should accept self signed certificates. The Care iOS App, for instance, is built to allow this for dev/qa builds but not for production builds.

For Android Devices:

 

  1. Under the settings tap on Wi-Fi.
  2. Make sure that the device is connected to the same network as your system is.
  3. Long press on the Wi-Fi to which the device is connected to. A pop over will be displayed.a1
  4. Tap on Modify Network.
  5. Select the ‘Show Advanced options’.                                                                       A2
  6. Tap on ‘None’ under ‘Proxy’ and select ‘Manual’ option.
  7. In the Proxy Hostname enter the IP address of the network to which your system is connected to.
  8. In Proxy port enter the port number – 8888.                                                                                       a3
  9. Open the mobile app and you should be able to observe HTTP traffic.

Conclusion:

In the above article i have covered how to configure Charles Proxy and how we can monitor the API request and response. This mainly comes handy while testing the native iOS and Android applications.

 

 

 

What is Deep linking ?

Deep linking is a technique for launching a mobile app from a web link. Deep linking allows an app to be opened to a specific screen, for some external event.

With deep linking, an app becomes more responsive and brings the user to a specific location.

For example, download the Twitter app. Log into it and then close it. Open the Safari browser and try to open URL www.twitter.com then iOS operating system opens the Twitter app.

Why Deep Linking?

While there are a lot of good reasons to use deep linking, here are a few that top our list.

– Switches from the web browser to the app directly,
– For launching different screens from external events,
– Communication between the apps, launching one app from another, and the exchange of data between the apps,
– URL based app navigation system.

Create a Xcode project: Open Xcode -> New -> Project -> Application -> Single View Application, Enter name and select swift.

Xcode_new_pjt

-> To enable deep linking, go to the info tab -> URL Types -> Click + button
-> Add the identifier and the URL scheme
-> To check if the URL Scheme is registered, go to Info.plist and check “URL types”, expanding that you see the scheme that registered
-> We can test that by opening the URL scheme in browser <Your_Url_Scheme>://

Add_Scheme

Now we need to launch the app using the URLs, which needs a function to be added in AppDelegate

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool{
}

URL : The complete URL, which is called to launch the app
sourceApplication : The identifier of application from where the URL is called
annotation : This is used to pass any additional data or any other information

The URL format is <Scheme>://<Host>/<Path>

Scheme : This is the scheme, which we have registered in our iOS app. This scheme tells iOS which app should be launched
Host : This is the website name or app name
Path : The path tells the information about launching screens

This isn’t just the end because we can do a lot more customization for launching screens, maintaining data between the apps etc.

I hope this post gave you a basic idea of how deep linking works using scheme. I’ll be back with more interesting posts soon.

Introduction
CocoaPods is a great tool to help with dependency management when building iOS or OS X applications.

CocoaPods is easy for managing third party libraries in same Xcode project. All the dependency libraries or projects can be maintained in a single file.

Install cocoaPods:
CocoaPods are distributed as Ruby gem. To check RubyGems is installed in your machine open terminal an type the following command

Make sure that your system is having updated gems, use this command to update gem

Once Ruby and RubyGems are installed, now we can install the cocoaPods

To install cocoapods run the following command in terminal

Create FrameWork :
Create a Xcode project Open Xcode -> New -> Project -> Framework & Library -> Cocoa Touch Framework
Enter framework name and select swift.

Create_Framework

If Framework is depending on any other frameworks create a pod file and add dependencies. Create Pod file and add dependency libraries

Update the pod file with dependencies your using, As per my requirement, i am using Alamofire library dependency in my Framework

As per my requirement, i am using Alamofire library dependency in my Framework

Install dependencies using following command

open wavelabs_ios_client_api.xcworkspace and add the required Swift classes and resources to framework.

This is the framework structure after installing pods.

Framework_folder

I have added API classes and Data models to my framework, Which is communicating to API server.  Now the framework looks like this

framework_dir

For using the cocoapods, we need a git repository to maintain the pod.
login/sign up to gitHub and create a repository and we can use the repository url later

Create PodSpec:
Pod spec describes the information of Pod library. It describes the details about name, version, description and files and resources used in the pod library

Create Pod spec documents using following commands

Edit podspec document

Commit Code to Git Repository:
Create a git repository and and run the following commands to push code

By using your git account you can login and commit the code to git

Now add and Update the podspec document also in git repository by using following command

Make sure that podspec document is validated with out any error.

Now we are ready to use our cocoa pod library.

If we want to update new version of cocoa pod library. We can make changes in framework and commit the change to git with new version.

Update the pod spec document with latest version and also push the latest pod spec doc. Then the new release will be available in gitHub.

Create an application using  cocoa pod library:

here is the example of using pod library in iOS Application.

Ever wondered if you could build an iOS application with basic functionalities as registration and social logins under a limited amount of time? On an average, it takes at least a week for us to build an iOS application and integrate registration and login functionalities with it. Why spend so much time on integrating those features into your app when you could focus on your product? Our iOS client library helps you build one under a matter of hours. It is a simple and secure user management for iOS developers. And what’s not to love? It’s easy to integrate with an iOS app.

In this post, I’ll walk you through building the iOS app seamlessly.

Requirements

  • iOS 8.0+ / Mac OS X 10.9+
  • Xcode 6.4

Installation

CocoaPods – CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects.

You can install CocoaPods tool on OS X by running the following command using the terminal.

Add the Wavelabs iOS Client Library to your iOS app

1) Create an Xcode Project on the local machine.

2) Open a terminal and cd to the directory containing the project.

3) Add your dependencies in the Podfile as shown here.

4) Save the file.

5) Run the command – pod install. This will install the SDK’s specifier in Podfile and dependencies that framework contains.

6) Open your app’s .xcworkspace file.

Usage

Register in api.wavelabs.in. Create a tenant (or) workspace and generate a clientID.

Add Baseurl and clientId in Targets/info as WavelabsAPISettings

WavelabsSettings_ClientID

Sample ‘AuthApi‘ Request:

AuthApi is using the custom delegate ‘getAuthApiResponseDelegate’, and wherever we want to use AuthApi, we need to set the AuthApi delegate.

User Login

iOS

iOS is a mobile operating system developed and distributed by Apple Inc. The operating system is based on the Macintosh OS X. iOS is designed for use with Apple’s multi-touch devices, iPhone, iPad, and iPod. This system responds to various gestures like  pinching, tapping and swiping.

Xcode

Xcode is the IDE for developing iOS and Mac apps, and the only one officially supported by Apple.

To install, simply download Xcode on the Mac App Store. It comes with the newest SDK and simulators, and you can install more stuff under Preferences > Downloads.

Xcode-download-1

Environment Setup

  • Download Xcode from App Store app on your Mac.
  • Xcode is downloaded into your /Applications directory.

Design and Implementation

1) AppDelegate- The Application Delegate is the class that receives application-level messages, including the applicationDidFinishLaunching message that’s most commonly used to initiate the creation of other views.

2) Storyboard- A storyboard is a visual representation of the app’s user interface, showing screens of content and the transitions between them.

3) ViewController-  View controllers are the vital link between an app’s data and its visual appearance. Whenever an iOS app displays a user interface, the displayed content is managed by a view controller or a group of view controllers coordinating with each other. Therefore, view controllers provide the skeletal framework on which you build your apps.

 Add a ViewController in Storyboard and Connect to Swift Class

– Open Main.storyboard, and select ViewController and drag it to the Storyboard

AddVc

–  Create a new swift file, File -> New -> file -> Select iOS -> Swift file. Then give it a name and it’s created.

AddFile

–  Give the swift class name for Created ViewController

ConnectVCToSwiftClass

Import iOS Starter App to Xcode

  • Open Xcode
  • Select -> Check out an existing project

OpenXcode

  • Enter repository location as git@scm.nbostech.com:starter-apps/starter-app-ios.git

Checkout1

  • Check out repository

Edit Bundle ID

Your bundle ID must be registered with Apple and be unique to your app. The bundle identifier is the unique string that identifies your application to the system.

  • In the project navigator, select the project(1) and your target(2) to display the project editor.
  • Click Info(3)
  • Enter the bundle ID in the Value column of the “Bundle identifier” row.(4)

 

BundleId

– Change base Url and client id  in Targets/info -> UrlSettings -> baseUrl

ChangeAppSettings

API  Modules

  1. Auth API
    1. Login
    2. Logout
    3. Change password
    4. Forgot password
    5. Refresh Token
  2. Users API
    1. SignUp
    2. Get Profile
    3. Update Profile
  3. Media API
    1. Get Media
    2. Upload Media
  4. SocialAPI
    1. ${social} login
    2. ${social} Connect

Models

  1. NewMemberApiModel
  2. MemberApiModel
  3. TokenApiModel
  4. SocialApiModel
  5. MediaApiModel
  6. MediaFileDetailsApiModel
  7. MessagesApiModel
  8. ValidationMessagesApiModel

Run iOS app 

  • Select iPhone 6 (select any one) in the Scheme pop-up menu in the Xcode toolbar.
  • Click the Run button (or press Command-R), located in the top-left corner of the Xcode toolbar.
  • You can watch the build process in the activity viewer of the Xcode toolbar.

RunIOSApp

 

Login

iOS_starter_Login

 

 

Input Output
[POST] http://localhost:8080/starter-app-rest-grails/api/v0/auth/login  [POST] http://localhost:8080/starter-app-rest-grails/api/v0/auth/login
{
“clientId”:”String”,
“accessToken”:”String”,
“expiresIn”:0
}
{

“member”: {
“id”: 0,
“email”: “string”,
“firstName”: “string”,
“lastName”: “string”,
“phone”: 0,
“description”: “string”,
“socialAccounts”: [
{
“id”: 0,
“email”: “string”,
“socialType”: “string”,
“imageUrl”: “string”
}
]
},

“token”: {
“scope”: “string”,
“expires_in”: 0,
“token_type”: “string”,
“refresh_token”: “string”,
“access_token”: “string”
}

}

Sign up

iOS_starter_SignUp

 

Input Output
[POST] http://localhost:8080/starter-app-rest-grails/api/v0/users/signup
 {

“clientId”: “string”,
“username”: “string”,
“email”: “string”,
“password”: “string”,
“firstName”: “string”,
“lastName”: “string”
}

{

“member”: {
“id”: 0,
“email”: “string”,
“firstName”: “string”,
“lastName”: “string”,
“phone”: 0,
“description”: “string”,
“socialAccounts”: [
{
“id”: 0,
“email”: “string”,
“socialType”: “string”,
“imageUrl”: “string”
}
]
},

“token”: {
“scope”: “string”,
“expires_in”: 0,
“token_type”: “string”,
“refresh_token”: “string”,
“access_token”: “string”
}

}

 

Profile

iOS Simulator Screen Shot Sep 3, 2015, 1.18.13 PM

Input Output
[GET] http://localhost:8080/starter-app-rest-grails/api/v0/users/{userId}
 

{

“id”: 0,
“email”: “string”,
“firstName”: “string”,
“lastName”: “string”,
“phone”: 0,
“description”: “string”,
“socialAccounts”: [
{
“id”: 0,
“email”: “string”,
“socialType”: “string”,
“imageUrl”: “string”
}
]
}

Change Password

iOS Simulator Screen Shot Sep 3, 2015, 1.18.20 PM

Input Output
[POST] http://localhost:8080/starter-app-rest-grails/api/v0/auth/changepassword
   {
“password”:”string”,
“newpassword”:”string”}
{
message = “string”;
messageCode = “string”;
}

Social Connects

iOS Simulator Screen Shot Sep 3, 2015, 1.18.16 PM

Input Output
[POST] http://localhost:8080/starter-app-rest-grails/api/v0/auth/social/${socialId}/connect
   {
“clientId”:”string”,
“accessToken”:”string”,
“expiresIn”:0
}
 

{
message = “string”;
messageCode = “string”;
}