Search Your Question

What is subclassing?

Ans : Subclassing is way of inheriting property of one class to another class. Child class inherit all behaviour of parent class. Let's talk about UIImageView.

NSObject > UIResponder > UIView > UIImageView

I have made one class as SpecialImageView which inherit UIImageView.  So SpecialImageView is subclass and UIImageView is parent class.

Suppose I want  5 imageview in my viewcontroller, which has default behaviour like borderWidth =2, broderColor = blue. 

So I have written this behaviour in SpecialImageView class once. All those 5 images are as SpecialImageView instead of UIImageView. 

So I do not need to write to all this behaviour for every 5 imageviews. So subclassing gives benefit of customisation of any class.


When we want custom UITableViewCell then we need to make subclass of UITableViewCell.

Difference between == and ===

Ans :  == checks equality and === checks identity. == check value of left side and right side are same or not. === check left side object and right side object point to same memory or not.

== used against int, float, string (value type) and === used against reference type (class type).

i.e

class SomeClass {
var a: Int;

init(_ a: Int) {
    self.a = a
}

}

var someClass1 = SomeClass(4)
var someClass2 = SomeClass(4)
someClass1 === someClass2 // false
someClass2 = someClass1
someClass1 === someClass2 // true

Explain Apple push notification working

Ans : Push notifications allow developers to reach users and perform small tasks even when users aren’t actively using an app.

In iOS 10, User can do following task :

  • Display a short text message
  • Play a notification sound
  • Set a badge number on the app’s icon
  • Provide actions the user can take without opening the app
  • Show a media attachment
  • Be silent, allowing the app to wake up in the background and perform a task
Now following steps to follow to configure push notification :

1. Create app id in developer account with your app bundle id. Push notification entitlement must be enabled for this app id. (or another way for go to App Settings > Capabilities and enable push notification switch). You also have to create CSR(Certificate Signing Request) file from your keychain and assign to this app id push notification feature in developer account.

2. Now in terms of coding, first we need to ask to user for allowing user notification. After allowing, we need to register for remote notification. If all goes good, system provides you 'token' which is address of this app for this device.

3. In code, first import usernotification. Then for registering for remote notification, in didFnishLaunchingWithOptions

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])  {
    (granted, error) in
   
       print("Permission granted: \(granted)")
    
       guard granted else { return }
       self.getNotificationSettings()

  }

 func getNotificationSettings()  {
       UNUserNotificationCenter.current().getNotificationSettings { (settings) in
       print("Notification settings: \(settings)")
       guard settings.authorizationStatus == .authorized else { return }
       UIApplication.shared.registerForRemoteNotifications()
  }


4. If registered for remote notification successfully, then one of the following two method will be called,

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)  {

       let tokenParts = deviceToken.map { data -> String in
              return String(format: "%02.2hhx", data)
        }

       let token = tokenParts.joined()
       print("Device Token: \(token)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error)  {
  print("Failed to register: \(error)")
}

5. Device token is provided by APNS and this token will be converted to string. This device token shold be sent to application server or stored to database on server side.

Now lets study about payload or notification message,

Payload looks like :

{
  "aps": {
    "alert": "Breaking News!",
    "sound": "default",
    "link_url": "https://raywenderlich.com"
  }
}

aps is fixed key in payload dictionary json. aps is also dictionary itself.

alert : Display text message
sound : Which sound when notification come
link_url : custom key, we can any such custom key for data
badge : number of count of badge that is displayed on app icon
category : which type of custom action notification have

Payload maximum size is 4096 kb (4 mb).


Now what when notification comes

1. If app is closed didFinishLaunchingWithOptions is called.
2. If open in background or foreground, then didReceiveRemoteNotification is called.

For 1st case,

In didFinishLaunchingWithOptions method
// Check if launched from notification

if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {

  let aps = notification["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

  (window?.rootViewController as? UITabBarController)?.selectedIndex = 1
}

For 2nd case,

In didReceiveRemoteNotification,

let aps = userInfo["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

Actionable Notification

Actionable notifications let you add custom buttons to the notification. You can put reply,retweet,like button as you seen our favourite apps. This type of notification can be defined by Category.

In this type notification, we have to register category like following instead of UIApplication.shared.registerForRemoteNotifications().

func registerForPushNotifications() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
    (granted, error) in   
    print("Permission granted: \(granted)")
 
    guard granted else { return }
 
    // 1
    let viewAction = UNNotificationAction(identifier: viewActionIdentifier,
                                          title: "View",
                                          options: [.foreground])
 
    // 2
    let newsCategory = UNNotificationCategory(identifier: newsCategoryIdentifier,
                                              actions: [viewAction],
                                              intentIdentifiers: [],
                                              options: [])
    // 3
    UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
 
    self.getNotificationSettings()
  }
}


Above things is not enough for taking action on button. We have to add extension of UNUserNotificationCenterDelegate.

Silent Notification 

If we want to do something task without knowing to user in background, then we can send silent notification to user device. For this background modes of push notification must be checked. For push notification aps, there is key named content-available. That's value should be 1 for silent notification.

For more detail, click here.



How to find current location?

Ans : 

Framework : MapKit
Class : CLLocationManager
Delegate : CLLocationManagerDelegate

Write NSLocationAlwaysUsageDescription and also its description in info.plist file.

Code :

@IBAction func setCurrentLocation(sender: AnyObject) {
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest

            if self.locationManager.respondsToSelector(#selector(CLLocationManager.requestAlwaysAuthorization)) {
                locationManager.requestAlwaysAuthorization() // request for authorisation for first time when app open
            } else {
                 locationManager.startUpdatingLocation()
            }
        }
    }


 //Updated location

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

//Get last updated location(current)

        let location = locations.last! as CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.20, longitudeDelta: 0.20))

//Set region of current location in map view with zooming

        self.mpView.setRegion(region, animated: true)

//Show current location (blue dot) on map
        self.mpView.showsUserLocation = true

    }

What is protocol? Why it is used?

Ans : Protocols are way to specify a set of methods that class has to implement if class want to work with this protocol. Protocol has 2 types of methods like Required type and Optional type methods.

1. If @required are tagged above methods, then these methods must be implemented on class which confirm this protocol.

2. If @optional are tagged above methods, then these methods is not necessary to implement on it.

Why it is used? 

Protocol provide blueprint methods for classes. It has certain methods and parameters that classes have to implement in its body. Its like that classes should have certain characteristic if it confirm protocol. Like if you want to become human(class) you must be sleep, eat, breathe(characteristics).

For more detail,
I have created Delegate and Protocol. See example.

What is category?

Ans : It is used to extend the functionality of the class. Implementation of category is in different file with name like classname + categoryname.h and .m file.

Read : Differnce between Category and Extension


Difference between Static Constructor and Private Constructor

Ans : I have asked this question for C# language.

Private Constructor :  It is used to prevent class to be instantiated and to be inherited. Class can have multiple private constructor and can be called by any other constructor.

Static Constructor :   It is used to initialise static members of a class. We can't say when it is called and It is called by CLR and not called by manually. It is called just before first instance of class is created. Class can have a only one static constructor. This constructor is called only once in lifetime of application.

What are higher order functinos in swift?

Ans : Higher order functions are functions that operate on other functions by taking function as argument or returning function.

 Sorted : Sorting array. It may takes closure as argument and returns array .
let numbers : [Int] =  [1,5,2,4,3]
let arrNumbers = numbers.sorted()

By default it returns in ascending order.

numbers.sorted(by: (Int,Int) -> Bool)  - > How we want to sort array then sorted(by:)
numbers.sorted((a,b) -> Bool in return a > b } // descending order
numbers.sorted(by : >)

      Map : It iterates through the array that is calling it and changes each element of the array based on the closure passes to the method.

Use map to loop over a collection and apply the same

operation to each element in the collection. It returns after

applying transform.

let arrInt = [1,8,4,6]
I want add 1 in every number in array.
Without loop, using map,

arrInt.map( $0 + 1)  // <- This is shortest code for doing map

output : [2,9,5,7]

How map works :

The map function has a single argument which is a closure (a

function) that it calls as it loops over the collection. This

closure takes the element from the collection as an argument and

returns a result. The map function returns these results in an

array.

Another example :

let chocolateAmt = [“Dairy Milk”:20.0, “Munch”:10]

I want to increase price 5%,
so using map,
chocolateAmt.map{ (key, value) in
   value + value*0.05
      }

output : [“Dairy Milk”:21.0, “Munch”:10.5]

Another Example :

If we want index in map,

let arrInt = [1, 2, 4, 5]
let indexElement = arrInt.enumerated().map { (index,element) in
return "\(index):\(element)"
}
print(indexElement) // [“0:1”, “1:2”, “2:4”, “3:5”]

CompactMap: Use this method to receive an array of nonoptional values when your transformation produces an optional value.

let scores = ["1", "2", "three", "four", "5"]

let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.

let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out. 


FlatMapFlatmap is used to flatten a collection of collections.

Flatmap is joined word of Flat + Map. So as per name, it applies map function over collection and do flatten collection.


Test 1 :

let codes = [["abc","def","ghi"],["jkl","mno","pqr"]]
let newCodes = codes.flatMap { $0.map {$0.uppercased()} }
print(newCodes)


Output : ["ABC","DEF","GHI","JKL","MNO","PQR"] 


Test 2 :

let codes = ["abc","def","ghi"]
let newCodes = codes.flatMap { $0.uppercased() }
print(newCodes)

Output : ["A","B","C","D","E","F","G","H","I"]

-> In Test 2, first it applies map so half output is like 

["ABC","DEF","GHI"] and after that it applies flat so now full 

output is : ["A","B","C","D","E","F","G","H","I"]


Tip : 

1. String is collection from Swift 4.

2.If you do flatmap a collection containing optional values, 

flatmap will only consider the non-nil values.

let codes = [1,2,nil,3,nil,5]

let newCodesFlatMap = codes.flatMap { return $0 }
output : [1,2,3,5]


let newCodesFlatMap = codes.map { return $0 }

output : [optional(1),optional(2),nil,optional(3),nil,optional(5)]


The output of map became a collection of optional int ([Int?]) 



only because the array had nil — value in it. Otherwise it would 



have been an Int array. It is benefit of using flatMap.



Filter : Return array with elements which fulfill filter condition.           
let numbersLessThanFive = numbers.filter { (a) -> bool in return a  <  5 }
let numbersLessThanFive = numbers.filter { $0 < 5}

          Reduce : It is used to combine all element in array to make one single value.
let sumOfNumbers = numbers.reduce(0, { $0 + $1 }) 

Difference between map and flatmap : 

Big difference is Map considers nil but flatmap  remove nil value from collection.


Difference between Delegate and NSNotification

Ans :  A delegate uses protocol and creates a has-a relationship between two classes. Benefit of delegate is that we can return something back to the owning class.
Notification is like point to multi-point communication. Notification is one way  of message transmitting way.

Delegates create relationship between two classes. Notifications are used to send events to one or many classes.

We have to use delegate to specified known object. Notification for all object.

Delegate is like talking over telephone. Notification is like radio station.  

Coding of NSNotificationCenter :

[[NSNotificationCenter defaultCenter] addObjserver:self selector:@selector(useNotificationWithString:)  name:@”TimeOut” object:nil];

For BroadCast,

[[NSNotificationCenter defaultCenter] postNotificationName:@”TimeOut” object:nil userInfo:dict];

-(void) useNotificationWithString:(NSNotification *)notification
{
            dict = [notification userInfo];
}

To Remove observer,
[[NSNotificationCenter defaultCenter] removeObserver];

What is delegate?

Ans : Delegate is means of communication between objects of iOS Applications. Delegate allows one object to send message to another object when an event occurs.

i.e
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”title” message:@”message” delegate:self cancelButtonTitle:@”Ok” otherButtonTitle:nil];

Here delegate is self. So now self is responsible for handling  all event fired by this instance of UIAlertView class.

Which button of UIAlertView is clicked, for that, event is clickedButtonAtIndex is called in or by Self or currentViewController.

Create PreDefined delegate :

  1. There are two ViewController NameVC and SurNameVC.
  2.  In NameVC, there are 2 textfield named as Name and FullName and 1 button as Submit.
  3. If I write in name and click on submit, it went to SurNameVC to take Surname parameter.
  4. On SurNameVC, after write Surname, on clicking of Submit, It call delegate method and went back to NameVC and Print Full Name in FullName textfield.

Implement above delegate and protocol in Objective-C : 


I have made protocol on SurNameVC like
    @protocol SurNameVCDelegate
      -(void)setSurName:(NSString *) strSurName;
    @end
    
    @property (nonatomic, retain) id delegate;

Now on NameVC submit button click, choose delegate of  SurNameVC object as self.

   objSurNameVC.delegate = self

and create method -(void)setSurName:(NSString *) strSurName;

on NameVC and it is called from surNameVC submit button. So setSurName is delegate method. We can print fullname by concatenating Name and Surname in FullName textfield.

So we delegate just pass message from one view controller to another view controller by delegate method.

Implement delegate and protocol in Swift

I have made custom UISlider. I want to send some value from custom UISlider value changed to view controller in which it is used. So for that, I have used delegate - protocol method.

customSlider.swift  Custom Slider file


import UIKit
protocol SliderDelegate: class {
    func sliderValueChanged(_ sender : UISlider)
}


class mpgpsSlider: UIView {
     
      weak var delegateSliderDelegate?

      required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "Slider", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        addSubview(view)
        
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for:                  .valueChanged)
    }

     @objc func sliderValueChanged(_ sender : UISlider)  {
        delegate?.sliderValueChanged(sender)
      }

}

ViewController.swift ViewController in which custom slider is used.

import UIKit

class VehicleProfileVC: BaseViewController,SliderDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        slider.delegate = self
    }
    
    func sliderValueChanged(_ sender: UISlider) {
        label.text = String(sender.value)
    }
}