iOS Revisited

Hot

Post Top Ad

1 Nov 2017

Structures VS Classes in Swift - iOS

11/01/2017 11:00:00 am 9
The difference between structure and class is that structure is a value type where class is a reference type.

We explain each one with a example.

Structures VS Classes in Swift - iOS

Classes:

A class is a blueprint or template for an instance of that class. The term "object" is often used to refer to an instance of a class.

Test following code in playground.

class Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having same reference
person2.name = "Nick"

print(person1.name) // Nick
print(person2.name) // Nick

Structures:

Structs are preferable if they are relatively small because copying is way safer than having multiple reference to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multi threaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

Test following code in playground.

struct Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having value with different references
person2.name = "Nick"

print(person1.name) // John
print(person2.name) // Nick

Read More

30 Oct 2017

Add Placeholder To UITextView in Swift 4 - iOS

10/30/2017 11:21:00 am 0
Swift provides default placeholder property to UITextField but not to UITextView.

So if you need a multi-line editable text view, you don’t get a pretty placeholder. Here you will learn how to add placeholder text to UItextView.


Here we will show step by step:

Step 1:

Firstly create new swift file and name it TextViewPlaceholder.swift and save it.

Next import UIKit and create extension to UITextView as follow:

import UIKit

extension UITextView: UITextViewDelegate {
// Code
}

Step 2:

Here we are going to add label as subview in order to show placeholder text. No worries it's quite simple.

Add the following code inside the extension:

override open var bounds: CGRect {
    didSet {
        self.resizePlaceholder()
    }
}

public var placeholder: String? {
    get {
        var placeholderText: String?
        
        if let placeholderLbl = self.viewWithTag(50) as? UILabel {
            placeholderText = placeholderLbl.text
        }
        
        return placeholderText
    }
    set {
        if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
            placeholderLbl.text = newValue
            placeholderLbl.sizeToFit()
        } else {
            self.addPlaceholder(newValue!)
        }
    }
}

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLbl = self.viewWithTag(50) as? UILabel {
        placeholderLbl.isHidden = self.text.characters.count > 0
    }
}

private func resizePlaceholder() {
    if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
        let x = self.textContainer.lineFragmentPadding
        let y = self.textContainerInset.top - 2
        let width = self.frame.width - (x * 2)
        let height = placeholderLbl.frame.height
        
        placeholderLbl.frame = CGRect(x: x, y: y, width: width, height: height)
    }
}

private func addPlaceholder(_ placeholderText: String) {
    let placeholderLbl = UILabel()
    
    placeholderLbl.text = placeholderText
    placeholderLbl.sizeToFit()
    
    placeholderLbl.font = self.font
    placeholderLbl.textColor = UIColor.lightGray
    placeholderLbl.tag = 50
    
    placeholderLbl.isHidden = self.text.characters.count > 0
    
    self.addSubview(placeholderLbl)
    self.resizePlaceholder()
    self.delegate = self
}

Above code will work in both orientations.

Step 3:

Here we will show how to use.

Simply add placeholder to UITextView as below:

let textView = UITextView()
textView.placeholder = "Start typing here"


Get the full code here.

Read More

28 Oct 2017

Argument of '#selector' refers to instance method that is not exposed to Objective-C | Add '@objc' to expose this instance method to Objective-C

10/28/2017 08:29:00 am 1
After installing Xcode 9 and migrating to Swift 4 from Swift 3 , @objc inference warning comes like below:

The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with “Use of deprecated Swift 3 @objc inference” logging enabled, and then disable inference by changing the “Swift 3 @objc Inference” build setting to “Default” for the “AppName” target.


If you introduce new methods or variables to a Swift class, marking them as @objc exposes them to the Objective-C run time. This is necessary when you have Objective-C code that uses your Swift class, or, if you are using Objective-C-type features like Selectors.

Fix compiler Errors:

We can fix this @objc inference warning by using two ways.

Solution 1:

One is to use @objc on each function or variable that needs to be exposed to the Objective-C run time as follow:

@objc func getSomeData() {

}

This is the best way for converting your code so that compiler doesn't complain.

Solution 2:

Second one is to add @objcMembers by a Class declaration as follow:

@objcMembers
class Photo {

}

This will automatically add @objc to ALL the functions and variables in the class.

This is a easy way but it increases the application size by exposing functions that did not need to be exposed.

Official Documentation

Read More

27 Oct 2017

Passing Data Using NotificationCenter in Swift 4

10/27/2017 11:21:00 am 0
Passing data from one view controller to another view controller using Notification Center is an easy way when compared to delegate protocols.

Here we need add observer or listeners for getting new data to load. First we need to send data using post notification method.


Let's take an example, Imagine an object X calls an object Y to perform an action. Once the action is complete, object X should know that Y has completed the task and take necessary action, this can be achieved with the help of Notification Center!

Follow step by step for better understanding.

Here we will pass data from second view controller to first view controller.

Sending Data - Post Notification:

First put some data as follow:

let dataToSend = ["name" : "John", "age" : 25] as [String : Any]

Add the following method for sending above data:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "newDataToLoad"), object: dataToSend)

Before sending data we need to listen for the above notification using NSNotification.Name.

Data Receiving - Add observer:

Add the following code for listening to new data:

NotificationCenter.default.addObserver(self, selector: #selector(notificationRecevied(notification:)), name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil)

Add the following method to retrieve data:

@objc func notificationRecevied(notification: Notification) {
    let data = notification.object
}

Remove Observer:

Don't forgot to remove observer on viewWillDisappear() as follow:

NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil)

Read More

26 Oct 2017

Store and Retrieve Image Locally Swift - Image Cache without Libraries

10/26/2017 11:47:00 am 1
Store images locally without using any other libraries. In this article we will store and retrieve images using our own code.

We are storing images in a Document Directory. It's different for each app, so we can store image inside Document Directory.

Save and Get Image from Document Directory in Swift ?Best practice to save Images locally ios,swift image cache library,How To Save An Image Locally In Xcode,Persisting Image Data Locally swift 4

Create sample Xcode project.

Storing Images:

First create new swift file and import UIKit as follow:

import UIKit

class SSCache: NSObject {

/..........

}

Add the following method for getting the current document directory:

private func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

Next create method for saving image locally, add following method:

func saveImage(image: UIImage, Key: String) {
    if let data = UIImagePNGRepresentation(image) {
        let filename = getDocumentsDirectory().appendingPathComponent("\(Key).png")
        print(filename)
        try? data.write(to: filename)
    }
}

In above method we are passing image and key for storing image.

Next add the following Singleton object:

static let sharedInstance = SSCache()

Usage:

We can use as follow for storing image.

Open ViewController.swift file and add the following code:

let image = UIImage(named: "bg.jpg")
SSCache.sharedInstance.saveImage(image: image!, Key: "backgroundImage")

Build and Run, now image stored locally.

So we can easily use in any class as above.

Get Image:

For getting image from document directory, add the following method inside SSCache class:

func getImage(Key: String) -> UIImage?{
    let fileManager = FileManager.default
    let filename = getDocumentsDirectory().appendingPathComponent("\(Key).png")
    if fileManager.fileExists(atPath: filename.path) {
        return UIImage(contentsOfFile: filename.path)
    }
    return nil
}

Here we need the image name for retrieving.

Usage:

Simple we can add the following line for getting image:

if let image = SSCache.sharedInstance.getImage(Key: "backgroundImage") {
    print("we got image \(image)")
}

Build and Run, we will get above message.

Download sample project with examples :
Read More

25 Oct 2017

Adaptive Autolayout Programmatically For iPhone X Using SafeAreaLayoutGuide - Swift 4

10/25/2017 10:46:00 am 0
Adaptive Autolayout mainly used to choose various layouts in different devices with orientations. Here in this article we create two layouts, one is for Portrait orientation and second on is for Landscape orientation. Here we are doing mainly for iPhone 10, so we have to use SafeAreaLayoutGuide.

Adaptive Autolayout Programmatically For iPhone X Using SafeAreaLayoutGuide - Swift 4


Create Project:

Firstly create new Xcode project.

Open ViewController.swift file and add the following properties:

let imgView : UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.image = UIImage(named: "kitten.jpg")
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    return imageView
}()

let sampleLabel : UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 0
    label.font = UIFont.systemFont(ofSize: 30.0)
    label.textAlignment = .center
    label.adjustsFontSizeToFitWidth = true
    label.text = "The Ragdoll is a cat breed with blue eyes and a distinct colourpoint coat. It is a large and muscular semi-longhair cat with a soft and silky coat. Like all long haired cats, Ragdolls need grooming to ensure their fur does not mat."
    label.textColor = UIColor.darkGray
    return label
}()

Here we are use kitten.jpg, replace that with your image.

ImageView Constraints:

The imageview should look like above image. So first add imageView to View then create constraints for imageView relatively to view.

Add the following method:

func addUIElements() {
    let guide = view.safeAreaLayoutGuide
    
    // imgView Layouts
    view.addSubview(imgView)
    let defaultImgTop = imgView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0.0)
    let defaultImgLeading = imgView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 0.0)
    
    // portrait
    let portraitImgTrailing = imgView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: 0.0)
    let portraitImgHeight = imgView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)

    // .....
}
Here we are using view's safeAreaLayoutGuide as base layout guide.

Label Constraints:

Label also should look like above image. So first add label to View then create constraints for label relatively to view.

Then add the following code to the end of addUIElements() method:

// sampleLabel Layouts
view.addSubview(sampleLabel)
let defaultLblTrailing = sampleLabel.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -10.0)
let defaultLblBottom = sampleLabel.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: 0.0)

// portrait
let portraitLblBottom = sampleLabel.topAnchor.constraint(equalTo: imgView.bottomAnchor, constant: 0.0)
let portraitLblLeading = sampleLabel.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 10.0)

So we successfully created layouts for imageview and label.

Next step is adding constraints to view. To do add the following line next to the constraints.

let defaultConstraints = [defaultImgTop, defaultImgLeading, defaultLblBottom, defaultLblTrailing, portraitImgHeight, portraitImgTrailing, portraitLblBottom, portraitLblLeading]
view.addConstraints(defaultConstraints)

Then finally call the addUIElements() method in viewDidLoad() and Run the project, we will output as follow:

Adaptive Autolayout Programmatically For iPhone X Portrait

That's Great! What about landscape?

Let's check, that's was bad layout in landscape.

Landscape Constraints:

So for Landscape create new layouts.

Add following code just before defaultConstraints creation:

// ImageView Landscape Constraints
let landscapeImgBottom = imgView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: 0.0)
let landscapeImgWidth = imgView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)

// Label Landscape Constraints
let landscapeLblTop = sampleLabel.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0.0)
let landscapeLblTrailing = sampleLabel.leadingAnchor.constraint(equalTo: imgView.trailingAnchor, constant: 10.0)

Next create two NSLayoutConstraint arrays, for that add the following properties:

var portraitConstraints: [NSLayoutConstraint] = []
var landscapeConstraints: [NSLayoutConstraint] = []

portraitConstraints is to store all constraints required for portrait orientation.
landscapeConstraints is to store all constraints required for landscape orientation.

Then replace defaultConstraints with the following code:

let defaultConstraints = [defaultImgTop, defaultImgLeading, defaultLblBottom, defaultLblTrailing]
portraitConstraints = [portraitImgHeight, portraitImgTrailing, portraitLblBottom, portraitLblLeading]
landscapeConstraints = [landscapeImgWidth, landscapeImgBottom, landscapeLblTop, landscapeLblTrailing]

Next add the observer to listen to orientation changes, add the following code in viewDidLoad() method:

NotificationCenter.default.addObserver(self, selector: #selector(self.toggleConstraints), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

Next add the method for toggle the constraints, add the following method:

@objc func toggleConstraints() {
    if UIDevice.current.orientation.isLandscape {
        view.removeConstraints(portraitConstraints)
        view.addConstraints(landscapeConstraints)
    }else {
        view.removeConstraints(landscapeConstraints)
        view.addConstraints(portraitConstraints)
    }
}

Next call the above method at the end of addUIElements() methods.

Now Build and Run, change the orientation we will see the following screen in landscape orientation.

Adaptive Autolayout Programmatically For iPhone X Landscape

Download sample project with examples :

Read More

23 Oct 2017

Premium Login UI/UX Design using Swift 4 Programmatically With Autolayouts

10/23/2017 11:16:00 am 8
Now a days mobile apps are using premium UI/UX designs. Login screen UI/UX design itself says how the app is gonna look further.

In this article we are going to create following login screen. We are not gonna use storyboard.

The whole screen developed programmatically using swift 4.

Premium Login UI/UX Design using Swift 4 Programmatically

You can download the whole code in the bottom of this article.

Getting Started:

Here we created new Xcode project and rename  ViewController.swift name to LoginVC.swift and changed the subclass in storyboard.

First we need create all required sub views. In the above picture we are having different sub views. So we create as follow:

let bgImageView : UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.image = UIImage(named: "bg.jpg")
    imageView.contentMode = .scaleAspectFill
    return imageView
}()

let logoImageView : UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.alpha = 0.8
    imageView.image = UIImage(named: "skull.png")
    imageView.contentMode = .scaleAspectFit
    return imageView
}()

// ............

Like above we created all subviews. Download & see the completed project for creating remaining subviews.

Next we are adding all created subviews to the main view. For that we created addingUIElements() method as follow:

func addingUIElements() {
    let padding: CGFloat = 40.0
    let signInButtonHeight: CGFloat = 50.0
    let textFieldViewHeight: CGFloat = 60.0
    
    // Background imageview
    self.view.addSubview(bgImageView)
    bgImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    bgImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    bgImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    bgImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
    
    // Background layer view
    view.insertSubview(bgView, aboveSubview: bgImageView)
    bgView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    bgView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    bgView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    bgView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
    
    // Logo at top
    view.insertSubview(logoImageView, aboveSubview: bgView)
    logoImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 60.0).isActive = true
    logoImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0).isActive = true
    logoImageView.heightAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4).isActive = true
    logoImageView.widthAnchor.constraint(equalTo: logoImageView.heightAnchor, constant: 0.0).isActive = true

    //.......

} 

In the above code we added three views as subview to main view. For more download project in the bottom of this article.

Here we created new class named TextFieldView subview of UIView. This view is for the textField,mailLogo and Line. So that we can reuse for multiple TextFields.

textField,mailLogo and Line

This example we shown here doesn't have any functionality yet, it's only design created programmatically.

Download sample project with examples :

Read More

22 Oct 2017

Latest iOS Interview Questions & Answers 2018

10/22/2017 02:58:00 am 10

Top 15 2017 2018 Swift Interview Questions & Answers pdf,10 Basic Swift Interview Questions to Practice with,25 ios interview questions and answers for junior developers,ios developer interview questions for experienced,swift 3.0 interview questions,swift technical questions,advanced swift interview questions,swift 4 interview questions

Question 1:

class Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1
person2.name = "Mike"

What's the value of person1.name and person2.name Would this be any different if Person was a class? Why?

Answer:

Both person1.name and person2.name are Mike.

Classes in Swift are reference types, and they are copied by reference rather than value. The following line creates a copy of person1 and assigns it to person2:

var person2 = person1

From this line on, any change to person1 will reflected in person2.

If Person were a structure, person1.name will be John, whereas person2.name will be Mike.
Structures in Swift are value types. Any change to a property of person1 would not be reflected into person2 and vice versa.

Question 2:

What is an optional in Swift and How it helps?

Answer:

An optional is used to let a variable of any type represent the lack of value. In Objective-C, the absence of value is available in reference types only, and it uses the nil special value. Value types, such as int or float, do not have such ability.

Swift extends the lack of value concept to both reference and value types with optionals. An optional variable can hold either a value or nil any time.

Question 3:

What is the difference between let and var in Swift?

Answer:

let kConstant = 10
var stringVariable : String

Here, we used the : string to explicitly declare that stringVariable will hold a string. In practice, it's rarely necessary — especially if the variable is given an initial value — as Swift will infer the type for you. It is a compile-time error trying to use a variable declared as a constant through let and later modifying that variable.

Question 4:

What is Completion Handler?

Answer:

Completion handlers are super convenient when our app is making an API call, and we need to do something when that task is done, like updating the UI to show the data from the API call. We’ll see completion handlers in Apple’s APIs like dataTaskWithRequest and they can be pretty handy in your own code.

The completion handler takes a chunk of code with 3 arguments:(NSData?, NSURLResponse?, NSError?) that returns nothing: Void. It’s a closure.

The completion handlers have to marked @escaping since they are executed some point after the enclosing function has been executed.

Question 5:

What is Singleton Pattern ?

Answer:

The Singleton design pattern ensures that only one instance exists for a given class and that there’s a global access point to that instance. It usually uses lazy loading to create the single instance when it’s needed the first time.

Question 6:

Closures  - value or reference types?

Answer:

Closures are reference types. If a closure is assigned to a variable and the variable is copied into another variable, a reference to the same closure and its capture list is also copied.

Question 7:

What are SQLite limits ?

Answer:

We need to define the relations between the tables. Define the schema of all the tables.

We have to manually write queries to fetch data.

We need to query results and then map those to models.

Queries are very fast.

Question 8:

What is CoreData ?

Answer:

Core data is an object graph manager which also has the ability to persist object graphs to the persistent store on a disk. An object graph is like a map of all the different model objects in a typical model view controller iOS application.

Question 9:

What are the execution states in iOS app?

Answer:

Not Running: The app is completely switched off, no code is being executed.

Inactive: The app is running in the foreground without receiving any events.

Active: The app is running in the foreground and receiving events.

Background: The app is executing code in the background.

Suspended: The app is in the background but is not executing any code.

Question 10:

What is AutoLayout?

Answer:

AutoLayout provides a flexible and powerful layout system that describes how views and the UI controls calculates the size and position in the hierarchy.

Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on constraints placed on those views

Read More

19 Oct 2017

Delegates Example in swift 4 | Pass Data with Delegation

10/19/2017 02:54:00 am 1
Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

Delegate helps in passing data back from presented view controller(SecondVC) to presenting view controller(FirstVC).

How Delegates Work?  Swift

Imagine an object X calls an object Y to perform an action. Once the action is complete, object X should know that Y has completed the task and take necessary action, this can be achieved with the help of delegates!

For better understanding of delegate we will go through sample application in swift, download or clone the starter project.

Build and Run we will see the following:

Delegates Example in swift 4 Starter

Here we are having FirstVC and SecondVC. FirstVC having quote and SecondVC is for changing the quote in FirstVC.

But now on tapping save button in SecondVC, the quote in FirstVC is not changing.

The problem is that this views are part of class Y and have no idea about class X, so we need to find a way to communicate between this two classes, and that’s where delegation helps.

We will follow step by step procedure to achieve delegation.

Step 1:

Open SecondVC and add the following protocol:

protocol SecondVCDelegate: class {
    func changeQuote(_ text: String?)
}

Here we are declaring only one method that accepts an optional String as an argument based on our requirement.

Step 2:

Create delegate property as follow:

weak var delegate: SecondVCDelegate?

Here we created a delegate property of protocol type and it should be optional.

Step 3:

Add the following line of code in saveQuote() method:

delegate?.changeQuote(textView.text)

Step 4:

Now open FirstVC and conform the protocol as following:

class FirstVC: UIViewController,SecondVCDelegate {

/......

Step 5:

Add the following method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let secondVC = nav.topViewController as? SecondVC {
        secondVC.delegate = self
    }
}

Here we are just creating an instance of SecondVC and assign its delegate to self, but what is self here? well, self is the FirstVC which has been delegated!

Step 6:

Finally add the function of the SecondVCDelegate protocol:

func changeQuote(_ text: String?) {
    quoteLabel.text = text
}

Build and Run , now we can change quote by using delegation.

 Delegates Example in swift 4 Final

Great you just completed delegations in swift.

Download sample project with examples :


Read More

18 Oct 2017

Convert String To Int, Float, Double in Swift 4

10/18/2017 05:48:00 am 0
We can easily convert String to Int, Float, Double using swift language.

Convert String To Int, Float, Double in Swift 4

String to Int:

By using Int constructor we can convert as follow:

let ageString = "25"

if let age = Int(ageString) {
    print(age)
} else {
    print("Not a valid string for conversion")
}

String to Float:

Same as Int, here we use Float constructor as follow:

let distanceString = "4.54" //in miles

if let distance = Float(distanceString) {
    print(distance)
} else {
    print("Not a valid string for conversion")
}

The string must contain a number as above, otherwise it will throw an error.

String to Double:

Same as Float, here we use Double constructor as follow:

let distanceString = "4.8765878" //in miles

if let distance = Double(distanceString) {
    print(distance)
} else {
    print("Not a valid string for conversion")
}

The string must contain a number as above, otherwise it will throw an error.
Read More

Post Top Ad