Passing Data Between ViewControllers

How do we pass data from one controller to another, there are many posts on this but this is the easiest way

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        // get a reference to the second view controller
        let secondViewController = segue.destination as! SecondViewController
        //secondViewController.receivedData
        // set a variable in the second view controller with the data to pass
        secondViewController.receivedBusinessData = business
    }    // method to run when table view cell is tapped

In the second view controller just add the variable, and you can access the data

var receivedBusinessData: Business? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        print("yy zz", receivedBusinessData?.name!)
        print("yy zz", receivedBusinessData?.address!)
        print("yy zz", receivedBusinessData?.id!)
        if(receivedBusinessData?.photos != nil ){
            for i in 0..<receivedBusinessData!.photos!.images.count{
                print("photos image url yy zz", receivedBusinessData!.photos!.images[i])
            }
        }        // Do any additional setup after loading the view.
    }

declare the variable in the second view, and you can access the data.

Dictionary Objects

Had a little bit of fun today, for some reason accessing a dictionary object by substring did not return the correct object.  So for future reference ALWAYS use

let photosarray = dictionary.value(forKey: “photos”)

Scratched my head about this for a few hours today.  Accessing by “forKey” is the correct reference per the Apple documentation

Adding Custom Cells to a tableView

Customize the cell in our own style – instead of using default table view style, We need a new cell type, so we can add multiple images, and or text in different places.

Drag and drop Table View Cell from utility area on UITableView.

customtableviewcell_swift_3

 

Now add an image view and a label from utility area to your prototype cell and adjust their size to look something like this:

customtableviewcell_swift_4

 

Here I have changed the color of the label to brown and and changed its default text to Name(you can change it to what ever color you like).Also I have increased the number of lines to 2.

customtableviewcell_swift_6

 

Ok, lets add the class to UITableViewCell

Right click on the project group>>New>>Cocoa Touch Class and press next.

add class name, select its parent class and choose Swift as Language if not already selected.

Here I am naming my class as CustomTableViewCell, it should be subclass of UITableViewCell

 

customtableviewcell_swift_4

Press next, choose the location where you want to save this class and press create.

Your project navigator should look like this:

customtableviewcell_swift_5

 

Now, Select the prototype cell from view controller(in storyboard) and add CustomTableViewCell as its class in utility area Under identity inspector

customtableviewcell_swift_7

also add same name(CustomTableViewCell) as its identifier just to make it little less confusing, under attribute inspector.

customtableviewcell_swift_8

 

Now, Add two IBOutlet inCustomTableViewCell class one for image and another for the name of the wonder and connect it to the image and label in CustomTableViewCell in viewController.

Here I have named my UIImageView as imageVW and UILabel as lblName

 

customtableviewcell_swift_9

Our inCustomTableViewCell class will look like this.

We are almost done now, Go to the cellForRowAtIndexPath method and replace the code with below code.

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {

var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(“CustomTableViewCell”) as! CustomTableViewCell

cell.imageVW.image = UIImage(named:self.arrImageName[indexPath.row])

cell.lblName.text = self.tableData[indexPath.row]

return cell
}
..

 

Here, we have first created an object for CustomTableViewCell class using the cell identifier that we set earlier.

then, we have just added value to its variable and we are Done.

Fun little Generic Linked List class

I use lists a lot

 


//  Created by frank on 1/15/19.

<span style="font-size: 14pt;">//  Copyright © 2019 frank. All rights reserved.

//

import Foundation

public class Node<T> {

    var value: T

    var next: Node<T>?

    weak var previous: Node<T>?

    

    init(value: T) {

        self.value = value

    }

}

public class LinkedList<T> {

    fileprivate var head: Node<T>?

    private var tail: Node<T>?

    private var currentNode: Node<T>?

    

    public var isEmpty: Bool {

        return head == nil

    }

    

    public var first: Node<T>? {

        return head

    }

    

    public var last: Node<T>? {

        return tail

    }

    public var current: Node<T>? {

        return currentNode

    }

    

    public func currentValue() -> T {

        

        if currentNode == nil{

            currentNode = head

        }

        let tValue = currentNode?.value

        

        currentNode = currentNode?.next

        return tValue!

    }

    

    public func currentIndexValue(index: Int) -> T {

        var node = head

        var count = 0

        while node != nil {

            

            if count == index{

                break

            }

            node = node!.next

            count = count + 1

            

        }

        return (node?.value)!

    }

    

    public func getNext() -> String {

        var text = ""

        

        text = "\(currentNode!.value)"

        

        currentNode = currentNode?.next

        if currentNode == nil{

            currentNode = head

        }

        return text

    }

    

    

    public func append(value: T) {

        let newNode = Node(value: value)

        if let tailNode = tail {

            newNode.previous = tailNode

            tailNode.next = newNode

        } else {

            head = newNode

            currentNode = head

        }

        tail = newNode

    }

    

    public func nodeAt(index: Int) -> Node<T>? {

        if index >= 0 {

            var node = head

            var i = index

            while node != nil {

                if i == 0 { return node }

                i -= 1

                node = node!.next

            }

        }

        return nil

    }

    

    public func removeAll() {

        head = nil

        tail = nil

    }

    public func getCount()->Int{

        var node = head

        var ecount = 0

        while node != nil {

            //text += "\(node!.value)"

            node = node!.next

            //if node != nil { text += ", " }

            ecount = ecount + 1

        }

        return ecount

    }

    

    public func remove(node: Node<T>) -> T {

        let prev = node.previous

        let next = node.next

        

        if let prev = prev {

            prev.next = next

        } else {

            head = next

        }

        next?.previous = prev

        

        if next == nil {

            tail = prev

        }

        

        node.previous = nil

        node.next = nil

        

        return node.value

    }

}

extension LinkedList: CustomStringConvertible {

    public var description: String {

        var text = "["

        var node = head

        

        while node != nil {

            text += "\(node!.value)"

            node = node!.next

            if node != nil { text += ", " }

        }

        return text + "]"

    }

}


 

 

 

Swift Libraries.. via Cocoapods

Lots of different abilities available via cocoapods..

To install to your project, open a terminal window

type “cd ” grab the project name from xcode, paste it next to the “cd ” press enter

You are now in the project directory

type “sudo gem install cocoapods”

type your password

Cocoapods should install for this project

For example lets say I want to install alamofire, and swiftyjson…. great ways to access url objects and parse the json that comes back.

In your terminal type “vi podfile”

You should see the editor

You will see something like this

target 'AppName' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!


  pod 'AFNetworking', '~&amp;amp;gt; 2.5'
  pod 'BDBOAuth1Manager'

  target 'AppName' do
    inherit! :search_paths
    # Pods for testing
  end

end

type “pod install” . you should see the pods install, and dont forget the include files within your swift code

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import GooglePlaces

let mapapikey = "YOUR MAP APIKEY"

class UrlSearch{
    
    func SearchMapAPi(latString: String)
    {
        
        //print( "|||||||| ", latString )
        let urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + latString + "&amp;amp;amp;amp;radius=500&amp;amp;amp;amp;type=restaurant&amp;amp;amp;amp;key=YOUR MAP APIKEY"
        print( urlString )
        /*let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=13.88068,100.43575&amp;amp;amp;amp;radius=300&amp;amp;amp;amp;type=restaurant&amp;amp;amp;amp;key=YOUR MAP APIKEY")!
        */
        let url = URL( string: urlString )
        
        
   
        AF.request(url!).responseJSON { response in
            switch response.result {
                case .success(let value):

                    let swiftyJsonVar = JSON(response.result.value!)
                    let placeArray = swiftyJsonVar["results"]
                

                    var currentPlaceObj :sPlace
                    
                   
                    for i in 0 ..&amp;amp;amp;lt; placeArray.count {
                        
                        let placeName = swiftyJsonVar["results"][i]["name"].string
                        let placeID = swiftyJsonVar["results"][i]["place_id"].string!
                        let placeAddress = swiftyJsonVar["results"][i]["vicinity"].string
                        let lat = swiftyJsonVar["results"][i]["geometry"]["location"]["lat"].double
                        let long = swiftyJsonVar["results"][i]["geometry"]["location"]["lng"].double
                        let locValue:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat!, long! );
                        
                     
                    }
                
                
                
                case .failure(let error):
                    print(error)
                }
           }
        }

The above is a code snippet to get the google places information from the json returned using alamofire and swiftyjson. Please note this is asynchronous

Welcome

Hello all and welcome to my new blog. Software engineer 17 years experience. I am setting up this blog for myself and others to read while I learn the Swift Programming language. Rather than take notes, I decided to write all my discoveries in a blog. I ask a lot of questions and find a lot of answers via the web, from tutorials, stack exchange, books, figuring out etc, but I thought it would be nice to put all this information in one place. Many times I find a solution to a question, and it may require that I add code because of discrepancies in the code, or the code may have been deprecated.

I will post solutions daily to this blog, including code snippets and full swift classes with examples that I have written for the application of the day. Hopefully others will find this useful, and this is a cool way for me to keep notes.