Search Your Question

What is meaning of _ in Swift func ?

Ans : 


The _ is used to define that the parameter is not named
If you have multiple _ it states that you do not need to name the parameters in your function call
func myFunc(name:String, _ age:String){       }

myFunc(Milo", "I'm a really old wizard")
If you do not use the underscore you would use 
myFunc(Milo, age: "I'm a really old wizard")
The _ is not necessary in function calls. It is just used to indicate that something does not to have a name.



Explain application states in iOS

Ans : 

There are 5 application states :

  1. Not Running
  2. Inactive
  3. Active
  4. Background
  5. Suspended.
iOS Application states
Application States


iOS Application Lifecycle : 

When an iOS app is launched the first thing called is

Initialise :

application: willFinishLaunchingWithOptions:-> Bool.
This method is intended for initial application setup. Storyboards have already been loaded at this point but state restoration hasn’t occurred yet.

Launch :

application: didFinishLaunchingWithOptions: -> Bool is called next. This callback method is called when the application has finished launching and restored state and can do final initialisation such as creating UI.

applicationWillEnterForeground: is called after application: didFinishLaunchingWithOptions: or if your app becomes active again after receiving a phone call or other system interruption.

applicationDidBecomeActive: is called after applicationWillEnterForeground: to finish up the transition to the foreground.

Termination :

applicationWillResignActive: is called when the app is about to become inactive (for example, when the phone receives a call or the user hits the Home button).

applicationDidEnterBackground: is called when your app enters a background state after becoming inactive. You have approximately five seconds to run any tasks you need to back things up in case the app gets terminated later or right after that.

applicationWillTerminate: is called when your app is about to be purged from memory. Call any final cleanups here.


Both application: willFinishLaunchingWithOptions: and application: didFinishLaunchingWithOptions: can potentially be launched with options identifying that the app was called to handle a push notification or url or something else. You need to return true if your app can handle the given activity or url.

Above all methods are defined in UIApplicationDelegate and AppDelegate.swift has to implement these methods.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!

What is app group capability in iOS?

Ans : 

If we ever needed to share data between your iOS apps and/or your application targets/extension/widgets , there’s a very easy way to do this using app groups. App group capability introduced with iOS 8.
To do so, we can enable the 'App Group' Capability.
  1. In Xcode’s Project Navigator, Click the 'Project Icon'
You can then use NSUserDefaults initWithSuiteName:.
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.example.app"];
Then set a value in one target…
[sharedDefaults setObject:value forKey:@"key"];
[sharedDefaults synchronize];
And read the associated value in the other target…
NSString *value = [sharedDefaults stringForKey:@"key"];

We can make file observer to be notified for changing value instantly. We can put observer on userdefault.plist file and being notified for some value changed in other application.


Note : BBPortal is example of this.


Can you search your app content In spotlight (search bar)?

Ans : 


Using spotlight search, here we can find loan no 14356 in our application and redirect to view details page of this loan number.

Apple offers us many iOS features that can boost our apps visibility even when the user is not using it. For example, features like Spotlight, Today Widget, iMessage, Push Notifications, Siri and so on...

Spotlight is a super-powerful search feature in iOS that searches through the contents of your installed apps that support it.

If we want our app content to appear in Spotlight, we need to use the CoreSpotlight framework. For creating searchable content we will need to be familiar with:

  • CSSearchableItemAttributeSet - specifies the properties that you want to appear in Spotlight (i.e. title, contentDescription, thumbnail). 
  • CSSearchableItem - this class represents the search item. We can assign a unique identifier for referring the object, a domain to manage the items in groups and attributeSet where we pass the CSSearchableItemAttributeSet that we have created for this object. 
  • CSSearchableIndex - a class that is responsible for indexing the content on Spotlight. It requires an array of CSSearchableItem.
Let's understand through some coding :

We have array of favourite books : 

var favorites = [Int]()   ->   This array contains int id of favourite book.

To enable searching content, we have to add our favourite list in spotlight content like following :

First import ,
import CoreSpotlight 
import MobileCoreServices

When new item added to favourite, it should be also added using following custom function :


func index(item: Int) {
    let book = books[item]

    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
    attributeSet.title = book[0]
    attributeSet.contentDescription = book[1]

    let item = CSSearchableItem(uniqueIdentifier: "\(item)", domainIdentifier: "com.iosiqabooks", attributeSet: attributeSet)
    CSSearchableIndex.default().indexSearchableItems([item]) { error in
        if let error = error {
            print("Indexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully indexed!")
        }
    }
}

Understanding above code :

Let's create CSSearchableItemAttributeSet object. This attribute set can store lots of information for search, including a title, description and image, as well as use-specific information such as dates (for events), camera focal length and flash setting (for photos), latitude and longitude (for places), and much more.

Regardless of what you choose, you wrap up the attribute set inside a CSSearchableItem object, which contains a unique identifier and a domain identifier. The former must identify the item absolutely uniquely inside your app, but the latter is a way to group items together. Grouping items is how you get to say "delete all indexed items from group X" if you choose to, but in our case we'll just use "com.iosiqaswift" because we don't need grouping. As for the unique identifier, we can use the project number.

To index an item, you need to call indexSearchableItems() on the default searchable index of CSSearchableIndex, passing in an array of CSSearchableItem objects. This method runs asynchronously, so we're going to use a trailing closure to be told whether the indexing was successful or not.

By default, search item expiry of 1 month. After 1 month, it is deleted from spotlight. We can manually set expiration date like :

item.expirationDate = Date.distantFuture : It will never expire.

If we want to remove content from spotlight or to disable search item for spotlight,

func deindex(item: Int) {
    CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ["\(item)"]) { error in
        if let error = error {
            print("Deindexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully removed!")
        }
    }
}

--------

We can now code for tapping on search result interaction in app delegate :

import CoreSpotlight in AppDelegate.swift.

We have to add following AppDelegate method :

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    if userActivity.activityType == CSSearchableItemActionType {
        if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
            if let navigationController = window?.rootViewController as? UINavigationController {
                if let viewController = navigationController.topViewController as? ViewController {
                    viewController.readBook(Int(uniqueIdentifier)!)
                }
            }
        }
    }

    return true
}

Credit : HackingWithSwift




Multiple option interview questions

What is the first method called in the iOS App initialisation flow? & what is the return type?
  • Main, , Return the is void.
  • App Delegate, Return type is Bool
  • UIApplicationMain, Return type is Bool
  • Main, Return type is int.

What is the parent class of App Delegate?
  • UIResponder
  • NSObject
  • UIApplicationMain
  • UIKit

What is the difference between [Foo new] and [[Foo alloc] init]?
  • New will not always initialize the object.
  • New is significantly faster than alloc + init.
  • None, they perform the same actions.
  • New does not exist in Objective-C.

What happens at runtime with the following :
    NSObject *obj1 = nil;
    NSObject *obj2 = [obj1 copy];
    NSLog(@"value of object 2  %@",obj2);
  • Application crashes with “SIGABRT”
  • Application continues, but issues “cannot access nil object reference” warning
  • Object 2 is instantiated as an NSObject with nil Values
  • Log prints “(null)” and continues as usual

What is the object.toString equivalent in Objective-C?
  • [NSObject toString];
  •  [NSObject description];
  • [NSObject stringWithFormat];
  •  [NSObject getDescription];

The format for a NSPredicate is the same as a Regular Expression
  • True
  • False

What can happen if you use “self” inside a block?
  • None of the above.
  • Self can become dangling pointer.
  • You can create a retain cycle.
  • By the time the block executes, self can be pointing to a different object[NSObject toString]

What is @dynamic directive meaning in iOS?
  • The @dynamic directive generates the accessor methods for you at compile time.
  • The @dynamic directive tells the compiler that you will provide accessor methods dynamically at runtime.
  • The @dynamic directive generates a getter method for your property at compile time.
  • The @dynamic directive generates a getter method for your property at run time.

You can use %@ to specify a dynamic property
  • True
  • False

What is difference between #import and #include?
  • #import ensures that a file is only ever included once, and #include allows the same thing.
  • None, they do the same thing.
  • #include is not valid syntax.
  • #include ensures that a file is only ever included once and #import permits the file to be included many times.

A UIView is a superclass of:
  • UIViewController
  • UIWindow
  • UIImage
  • UILabel
  • UIScreen

A method and a variable can have the same name in Objective C.
  • True
  • False

What framework is KVO (Key Value Observing) a part of?
  • Foundation
  • UIKit
  • CoreData
  • UIKItCore

What class method is used to make an NSArray from NSData class?
  • NSArray arrayWithObject:
  • NSArray dataWithContentsOfFile:
  • NSData dataWithContentsOfFile:
  • NSKeydUnarchiver unarchiveObjectWithData:

In Core Data, what is the name of the object representation for the database schema?
  • NSManageObjectContext
  • NSManagedObjectModel
  • NSEntityDescription
  • NSManagedObject

What’s the difference between “nil” and “NULL” ?
  • nil is a literal null value for Objective-C instances. NULL is object used to represent null.
  •  nil is a literal null value for Objective-C instances. NULL is literal null value for Objective-C classes.
  • Nil is a literal null value for Objective-C instances. NULL is literal null value for C pointers.
  • NULL is literal null value for Objective-C instances. Nil is literal null value for C pointers
  • they are the same thing


Which of the following is Singleton class?
  • NSFileManager
  • UIApplication
  • NSFileManger & UIApplication
  • NSArray & NSDictionary
  • NSString & NSOperations

What is the output of the below program?

    NSMutableString *tempString = [NSMutableString stringWithString:@"1"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [tempString appendString:@"2"];
        NSLog(@"%@",tempString);
    });
    [tempString appendString:@"3"];
    NSLog(@"%@",tempString);


  • Log prints “13” & “132” and continues as usual.
  • Log prints “12” and then we will have a deadlock here because the main queue will block.
  • Log prints “123” and continues as usual.
  •  Log doesn’t print anything. It’s deadlock here because the main queue will block on the call to dispatch_async.

What is the output of the below program?

    NSMutableString *tempString = [NSMutableString stringWithString:@"1"];
    dispatch_sync(dispatch_get_main_queue(), ^{
        [tempString appendString:@"2"];
        NSLog(@"%@",tempString);
    });
    [tempString appendString:@"3"];
    NSLog(@"%@",tempString);
  • Log prints “13” & “132” and continues as usual.
  • Log prints “12” and then we will have a deadlock here because the main queue will block.
  • Log prints “123” and continues as usual.
  •  Log doesn’t print anything. It’s deadlock here because the main queue will block on the call to dispatch_async.

What is used to sort Core Data results?
  • NSSort
  • NSCoreDataSort
  • [self sort]
  • NSSortDescriptor
  • NSPredicate

Note : Answer is written in Bold.