Swift iOS 9 iPhone Accelerator Application

Open Xcode and select Create a new Xcode project.

Welcome to Xcode

Welcome to Xcode

Select Single View Application and click Next.

Single View Application

Single View Application

For product name, use IntellijSwiftAccelerator and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices. Click Next.

P.S: Don’t forget to untick Include Unit Tests and Include UI Tests.

Open Main.storyboard. Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Ctrl + Drag from the Label to the File’s Owner and make the connection with the corresponding properties.

Accelerator ViewController

Accelerator ViewController

Create a new ViewController.

Cocoa Touch Class

Cocoa Touch Class

UIViewController

UIViewController

Then make sure you attach this file into view controller in Identity inspector.

Identity inspector -UIViewController

Identity inspector -UIViewController

The other properties are needed to update the Labels with the axes values. Go to ViewController.swift and add 3 UILabels to the main View.

Outlet – xAxis

Outlet – xAxis

Outlet – yAxis

Outlet – yAxis

Outlet – zAxis

Outlet – zAxis

Open AcceleratorViewController.swift and update the with this code.

import UIKit
import CoreMotion

class AccelerometerViewController: UIViewController {

    var motionManager: CMMotionManager = CMMotionManager()
    @IBOutlet weak var xAxis: UILabel!
    @IBOutlet weak var yAxis: UILabel!
    @IBOutlet weak var zAxis: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.motionManager.accelerometerUpdateInterval = 1;
        
        if (self.motionManager.accelerometerAvailable)
        {
            self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
                (data, error) in
                dispatch_async(dispatch_get_main_queue()) {
                    self.xAxis.text = String(data!.acceleration.x)
                    self.yAxis.text = String(data!.acceleration.y)
                    self.zAxis.text = String(data!.acceleration.z)
                }
            }
            
        } else {
            print("not active")
        }
    }
}

Swift iOS 9 iPhone Camera Application

Open Xcode and select Create a new Xcode project.

Welcome to Xcode

Welcome to Xcode

Select Single View Application and click Next.

Single View Application

Single View Application

For product name, use IntellijSwiftCamera and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices. Click Next.

P.S: Don’t forget to untick Include Unit Tests and Include UI Tests.

Open Main.storyboard. Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

This is a very simple user interface consisting of an image view, a toolbar and two bar button items. (Don’t forget to set AutoLayout).

Camera ViewController

Camera ViewController

Create a new ViewController.

Cocoa Touch Class

Cocoa Touch Class

 

UIViewController

UIViewController

Then make sure you attach this file into view controller in Identity inspector.

Identity inspector -UIViewController

Identity inspector -UIViewController

Select the image view object in the view canvas, display the Assistant Editor panel. Ctrl-click on the image view object and drag to a position just below the class declaration line in the Assistant Editor. Release the line, and, in the resulting connection dialog, establish an outlet connection named imageView.

Outlet - imageView

Outlet – imageView

Open CameraViewController.swift and update the with this code.

import UIKit
import MobileCoreServices

class CameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var imageView: UIImageView!
    var newMedia: Bool?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

With the Assistant Editor still visible, establish action connections for the two buttons to methods named useCamera and useCameraRoll respectively (keeping mind that it may be necessary to click twice on each button to select it since the first click will typically select the toolbar parent object).

Action - userCamera

Action – userCamera

 

Action - useCameraRoll

Action – useCameraRoll

Open CameraViewController.swift and update the with this code for useCamera and useCameraRoll functions.

    @IBAction func useCamera(sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            
            let imagePicker = UIImagePickerController()
            
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
            imagePicker.mediaTypes = [kUTTypeImage as String]
            imagePicker.allowsEditing = false
            
            self.presentViewController(imagePicker, animated: true, completion: nil)
            newMedia = true
        }
    }
    
    @IBAction func useCameraRoll(sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum) {
            let imagePicker = UIImagePickerController()
            
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            imagePicker.mediaTypes = [kUTTypeImage as String]
            imagePicker.allowsEditing = false
            self.presentViewController(imagePicker, animated: true, completion: nil)
            newMedia = false
        }
    }

Writing the Delegate methods in CameraViewController.

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
        if mediaType == kUTTypeImage as String {
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            
            imageView.image = image
            
            if (newMedia == true) {
                UIImageWriteToSavedPhotosAlbum(image, self, #selector(CameraViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
            }
        }

    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) {
        
        if error != nil {
            let alert = UIAlertController(title: "Save Failed",
                                          message: "Failed to save image",
                                          preferredStyle: UIAlertControllerStyle.Alert)
            
            let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
            
            alert.addAction(cancelAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

Results.

Screenshot 1

Screenshot 1

 

Screenshot 2

Screenshot 2

Building a To Do List iOS Mobile App – Part 2

In the first part of the simple iOS mobile app (toDoList) tutorial series, you covered the basics of setting environment and user interface.

We’ll start where we left off last tutorial, so open your project from last time, or go through the previous tutorial first. http://intellij.my/2016/09/03/building-a-to-do-list-ios-mobile-app-part-1/

Select UITableViewController in Main.Storyboard and edit Attribute Inspector according to this setting:

Style: Basic
Identifier: TaskCell
Accessory: Disclosure Indicator

Attribute Inspector.

Attribute Inspector.

 

UiTableViewController

UiTableViewController

Go to UIViewController and make sure the user interface is similar like this one. Don’t forget to set constraints for each elements. If you don’t know how to do it, feel free to refer it here, https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/DesigningaUserInterface.html.

UIViewController

UIViewController

Create two Cocoa Touch Class. One is TableViewController.swift(UITableViewController) and the other one is ViewController.swift(UIViewController).

Xcode 7.3.1 – New File

Xcode 7.3.1 – New File

 

Cocoa Touch Class

Cocoa Touch Class

 

UITableViewController

UITableViewController

 

UIViewController

UIViewController

Then make sure you attach both files into each controllers in Identity inspector.

Identity inspector – UITableViewController

Identity inspector – UITableViewController

 

Identity inspector -UIViewController

Identity inspector -UIViewController

Open Info.plist and add these code at the end third last line of code before tag.

...
</array>
<key>NSAppTransportSecurity</key>
	<dict>
	<key>NSAllowsArbitraryLoads</key>
	<true/>
	</dict>
</dict>
</plist>

Open TableViewController.swift and update the with this code.

import UIKit
import Alamofire
import SwiftyJSON

class TableViewController: UITableViewController {

    var id: String!
    var name: String!
    var descriptions: String!
    var tasks:[JSON] = []
    
    @IBAction func addNewTask(sender: AnyObject) {
        self.id = nil
        self.performSegueWithIdentifier("MySegue", sender: self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
    }
    
    override func viewWillAppear(animated: Bool) {
        loadData()
    }
    
    func loadData() {
        Alamofire.request(.GET , "http://demo.revivalx.com/todolist-api/get_all_tasks.php", parameters: [:])
            .responseJSON { response in
                if response.result.isSuccess {
                    var jsonObj = JSON(response.result.value!)
                    if let data = jsonObj["tasks"].arrayValue as [JSON]?{
                        self.tasks = data
                        self.tableView.reloadData()
                    }
                }
        }
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath)
        let task = tasks[indexPath.row]
        cell.textLabel?.text = task["name"].stringValue
        return cell
    }
    
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            let task = tasks[indexPath.row]
            Alamofire.request(.GET , "http://demo.revivalx.com/todolist-api/delete_task.php", parameters: ["taskId":task["taskId"].stringValue])
                .responseJSON { response in
                    if response.result.isSuccess {
                        self.loadData()
                    }
            }
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let task = tasks[indexPath.row]
        id = task["taskId"].stringValue
        name = task["name"].stringValue
        descriptions = task["description"].stringValue
        self.performSegueWithIdentifier("MySegue", sender: self)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "MySegue" {
            let viewController: ViewController = segue.destinationViewController as! ViewController
            viewController.id = id
            viewController.name = name
            viewController.descriptions = descriptions
        }
    }
}

Open ViewController.swift and replace the with this code.

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {

    @IBOutlet weak var txtName: UITextField!
    @IBOutlet weak var txtDescription: UITextField!
    var id: String!
    var name: String!
    var descriptions: String!
    var tasks:[JSON] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if id != nil {
            txtName.text = name
            txtDescription.text = descriptions
        }
    }

    @IBAction func btnSubmit(sender: AnyObject) {
        if id != nil {
            Alamofire.request(.POST , "http://demo.revivalx.com/todolist-api/update_task.php", parameters: ["taskId":id,"name":txtName.text!,"description":txtDescription.text!])
                .responseJSON { response in
                    if response.result.isSuccess {
                        self.navigationController?.popViewControllerAnimated(true)
                    }
            }
        } else {
            Alamofire.request(.POST , "http://demo.revivalx.com/todolist-api/create_task.php", parameters: ["name":txtName.text!,"description":txtDescription.text!])
                .responseJSON { response in
                    if response.result.isSuccess {
                        self.navigationController?.popViewControllerAnimated(true)
                    }
            }
        }
    }
}

Building a To Do List iOS Mobile App – Part 1

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.

swift programming language

swift programming language

Here are some of features:

  1. Modern
  2. Designed for Safety
  3. Fast and Powerful
  4. Interactive Playgrounds
  5. Ready Today
  6. Read-Eval-Print-Loop (REPL)

Reference: https://developer.apple.com/swift/

Getting Started.

Before we start this tutorial, make sure you already setup your machine (mac) with these tools:

  1. Xcode 7.3.1 – https://developer.apple.com/xcode/downloads/

Open Xcode and select Create a new Xcode project.

Welcome to Xcode

Welcome to Xcode

Select Single View Application and click Next.

Single View Application

Single View Application

For product name, use IntellijSwiftToDoList and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices. Click Next.

P.S: Don’t forget to untick Include Unit Tests and Include UI Tests.

IntellijSwiftToDoList

IntellijSwiftToDoList

Install CocoaPods using terminal. What is CocoaPods?

CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem.

Reference: https://guides.cocoapods.org/using/getting-started.html

Open your terminal and type this command.

sudo gem install cocoapods

Go to your directory and initialize your pod using this command.

cd /Users/MNurdin/Documents/iOS/IntellijSwiftToDoList
pod init

Open your finder and edit pod file (Podfile) with these one.

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

use_frameworks!

target 'IntellijSwiftToDoList' do
	pod 'Alamofire', '~> 3.4'
end

Go back to your terminal and run pod install to install all the dependencies. It takes a few of minutes to download.

pod install

After finish downloading, open IntellijSwiftToDoList.xcworkspace file, not IntellijSwiftToDoList.xcodeproj because we want to use the pod.

Storyboards and interface builder

Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Delete ViewController.swift and ViewController on the Main.Storyboard. Drag a Table View Controller and View Controller to Main.Storyboard.

Main.Storyboard

Main.Storyboard

Select Table View Controller and navigate to Attributes inspector. Tick Is Initial View Controller.

Attributes inspector

Attributes inspector

Select the Table View Controller again and in the menu go to Editor > Embed In >Navigation Controller. This adds a Navigation Controller to the storyboard with an initial scene.

Editor > Embed In > Navigation Controller

Editor > Embed In > Navigation Controller

Select the Navigation Item under the Table View Controller, and in the Attributes Inspector type To Do List as the Title.

Navigation Item

Navigation Item

From the Object Library, drag a Bar Button Item to the right of the navigation bar on the Table View Controller. Select the Bar Button Item (which has a default value of “Item”) and in the Attributes Inspector, in the Identifier option, choose Add. This will change the button to the add symbol (+).

Bar Button Item

Bar Button Item

Select the Table View Controller, press control button and drag to View Controller like image below. We added a segue. Name it MySegue in Show the Attributes Inspector > Identifier.

Next tutorial, part 2 here http://intellij.my/2016/09/20/building-a-to-do-list-ios-mobile-app-part-2/