Shrikar Archak

It does not matter how slow you go so long as you do not stop. ~Confucius

iOS Swift Tutorial: Fitness Tracking and iOS Charts

In the previous tutorial we found how to use the CMPedometer and CMActivityManager to fetch the steps and the current activity state.

This is how the graph will look

images

Lets look at the change in the main storyboard from the previous tutorial

  • First create a new file called ChartViewController.Swift which is a subtype of UIViewController. (File New -> iOS Source -> Cocoa Touch Class)
  • In the identity inspector set the type to ChartViewController. images

  • Add a button dismiss to the viewcontroller

  • Create a IBAction from dismiss to the ChartViewController( Use the CTRL+Drag trick. CTRL+DRAG from dismiss button to the ChartViewController)
  • Drag a UIView from the object library on to the ChartViewController and setup the autolayout constraints as below. images

  • Select the UIView go to Identity inspector and change the Class to BarChartView. images

  • CTRL+DRAG from uiview on to the ChartViewController and create a IBOutlet with name as chartView

iOS Swift Development : Step Counter App Using Pedometer Data

Apple’s Motion CoProcessor provides a lot of details with respect to motion tracking. We will be building a simple step counter app which uses a pedometer object to retrieve step counts and other information about the distance traveled and the number of floors ascended or descended. The pedometer object manages a cache of historic data that you can query or you can ask for live updates as the data is processed.

The CMMotionActivity class contains the data for a single motion update event. On devices that support motion, you can use a CMMotionActivityManager object to request updates when the current type of motion changes. When a change occurs, the update information is packaged into a CMMotionActivity object and sent to your app.

CMMotionActivity contains state related to many of the activites like stationary, walking, running, automative, cycling and unknown. Also along with that it provides confidence about how accurate the motion data is.

CMPedoMeter and CMMotionActivityManager will work on actual devices.

In the mainstory board let go ahead and start adding the UILabel’s and UIImageview.

  • Add Labels for the Today,Steps,Activity state.
  • Add imageview for the shoe and the state (Either running, walking, stationary,automotive)
  • Setup the IBOutlet for all the above.
  • More on autolayouts AutoLayout Part 1 and Autolayout part 2

images

Parse Search in iOS 8 With Swift

I have been getting a lot of requests to show how to implement search in Parse using Swift. Previously I had shown how to implement search : UISearchBar and UISearchBarDelegate if you haven’t checked that before I suggest you to take a look at it to get an overall idea.

Lets dive directly into code and I will explain what it does. Most of the code is boilerplate code for UITableViewController. The main function is to take the search text and implement the search functionality. In this case we would ideally want the search to be done on the server side and not client side hence we make use of the where key for containsString in the PFQuery class to perform search on server side and return the results.

ParseSearch.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
//  ParseSearchTableViewController.swift
//  SwiftSearch
//
//  Created by Shrikar Archak on 3/31/15.
//  Copyright (c) 2015 Shrikar Archak. All rights reserved.
//

import UIKit

class ParseSearchTableViewController: UITableViewController, UISearchBarDelegate {


    @IBOutlet weak var searchBar: UISearchBar!
    var searchActive : Bool = false
    var data:[PFObject]!
    var filtered:[PFObject]!
    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.delegate = self
        /* Add some data,Run once with this code uncommented to create dummy data in parse */
//        for index in 1...10{
//            let obj = PFObject(className: "SearchText")
//            obj["text"] = "Text here \(index)"
//            obj.save()
//        }
        search()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func search(searchText: String? = nil){
        let query = PFQuery(className: "SearchText")
        if(searchText != nil){
            query.whereKey("text", containsString: searchText)
        }
        query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
            self.data = results as? [PFObject]
            self.tableView.reloadData()
        }

    }


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

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(self.data != nil){
            return self.data.count
        }
        return 0
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        let obj = self.data[indexPath.row]
        cell.textLabel!.text = obj["text"] as? String
        return cell
    }

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchActive = true;
    }

    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        search(searchText: searchText)
    }

}

If the amount of data you are searching is small this approach might be ok, but this is not ideal for full text search. You can also take a look at this blog post http://blog.parse.com/2013/03/19/implementing-scalable-search-on-a-nosql-backend/ for understanding how it can be done efficiently

iOS 8 Custom Transitions in Swift

iOS provides a few transitions like Modal, Push and a few more. But if you want to make your app looks different and want to have light weight transitions within your app then you are in for a treat with Custom transitions.

Lets try to implement the same in our How to make a photography inspiration appand Part 2 Swift iOS Tutorial: Taming UITableView Visual Blur and Autolayout.

images

There are a few things which we need to make custom transitions work.

Our view controller which will begin the transition should implement the UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning

Lets create a DetailViewController which has an imageview within that and setup the autolayout constraints with value 0 to superview on all the sides. If we want to go to a detailViewController on selecting a tableView cell we could implement our tableView didSelectRowAtIndexPath as below

didSelectRowAtIndexPath
1
2
3
4
5
6
7
8
9
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let dvc = DetailViewController(nibName: "DetailViewController", bundle: nil)
    dvc.photo = self.photos[indexPath.row]
    dvc.transitioningDelegate = self
    dvc.modalPresentationStyle = UIModalPresentationStyle.Custom
    let currRect = self.tableView.rectForRowAtIndexPath(indexPath)
    self.point = CGPointMake(currRect.midX, currRect.midY)
    self.presentViewController(dvc, animated: true, completion: nil)
}

The key thing to note here are the setting up of transitioningDelegate to self and the modalPresentationStyle to UIModalPresentationStyle.Custom. Once we have set this up we can present the view controller.

Next we need to implement the functions which will perform the actual transitions.

AnimationControllers
1
2
3
4
5
6
7
8
9
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresenting = true
    return self
}

func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresenting = false;
    return self
}

Swift iOS Tutorial: Taming UITableView Visual Blur and Autolayout

This is the part 2 of Building a Photography inspiration app if you haven’t looked at the part 1 I strongly suggest you to complete that part before continuing.

In the previous post we have successfully converted the json into a domain specific model like Photo. Instead of dealing with json directly we will be using the photo model in our view controllers.

UITableView is one of the versatile class which can be used in many different usecases. We will be using UITableView to display a list of Photos in our application along with the exif data associated with the Photo.

Lets get started with our app in Xcode 6.

  • Delete the existing viewcontroller on the mainstory board and drag a uitableview controller from the object library on to the mainstory board. images
  • Create a PhotoListController class which is a subclass of UITableViewController.
  • Create a PhotoCell class which will be a subclass of UITableViewCell.
  • Select the PhotoListController and in the identity inspector set the class as PhotoListController. images
  • Similarly select the PhotoCell and set the class as PhotoCell.
  • Next step is customizing the PhotoCell.
    • Drag a imageview
    • Drag a visual blur view on top of imageview at the bottom.
    • Drag multiple uilable for each of the camera, iso, shutterspeed etc.
    • Select the element and arrange them approximately how you want them to be laid out.