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.

GIT for Interview

1. Difference between Distributed & Central version control system.
A. GIT is distributed version control system.
     SVN is central version control system.

Central Version Control System : It is located in one place and people can check out from central location to make their changes and then check everything back in but some times it is problematic if central repository is corrupted or central system is not connected through network. For that we have to take backup manually in local machine.

Distributed Version Control System : Everybody has local repository. Your local repository has all information that remote repository has and till last sync done between local and remote repository. So sometimes, if remote repository is not able to be connected through internet, then we can see every changes as it is also saved in local repository. So every developer has repository in locally. So it is called in distributed version control system.


 2. Check version of GIT installed on your machine.
A. git --version

3. Setting configuration
A.
Set username : git config --global user.name "Manan Shah"
Set email : git config --global user.email "manan0shah@gmail.com"
Check configuration setting : git config --list

4. Get git function help
A.

git help <verb>
git verb --help

i.e git help config
     git config --help

     git help add
     git add -help

5. Setup git in your project
A. Goto finder/folder of project which we want to track, using terminal using cd command and write following command
 git init

6. To check status of untracked files in our repository
A. git status

7. Ignore files which we want to keep untracked. Like personal settings, preferences, etc
A. Create a gitignore file : touch .gitingore
     Write down list of files which we want to ignore to track as below :
     .ds_store
     .xcodeproj
     *.py  (wild card used to ignore files which has py extension)

After this, git status

--------------------------------------------

There are 3 area in area we have knowledge about.
1. Working directory
2. Staging Area
3. Git directory

(image from Pro Git" book : https://git-scm.com/book/en/v2)

1. Working directory : Untracked files reside in working directory. -> Files in red colour in terminal
2. Staging Area : When we use command git add . , then this files added to staging area. Which can be committed. -> Files in green colour in terminal
3. Git directory : When we commit our changes, then it goes to git directory. That can be push to remote directory. git commit -m "message for this commit like changes in setting"

Note : If we want to uncommit changes or remote files from staging area to working directory, then Use git reset 

We can check all commit log using command : git log

------------------------------------------

Cloning git repo

git clone <url_of_remote_git> <local_directory>

git clone https://....../remote_repo.git .    (. means in current folder)

-----------------------------------------

Viewing remote repository info

git remote -v  : Give information about your local repository path for fetch, push

git branch -a : Give list of all local and remote branches

-----------------------------------------

Pushing code

git diff : tells difference between remote and local files changes
git pull origin master : pull all changes made from remote repo to local
git push origin master : push all changes from local to remote repo

-----------------------------------------

Merge branch

Suppose, we have worked on calc branch and we need to merge calc branch into master branch.

git checkout master :  Switch to master branch or in which we have to merge
git pull origin master : Pull all changes in master branch from remote server
git branch --merged : Check branch name in which code is to be merged
git merge calc : Merge calc branch with master branch. It shows number of changes. If any conflicts are there, then  we have to solve it using editing code.
git push origin master : Push merged code to remote master branch

-----------------------------------------

Deleting branch

git branch -d calc : Delete calc branch locally
git branch -a : To check whether branch is deleted or not.
git push origin --delete calc : To delete calc branch remotely

-----------------------------------------------------------------------------------------------------------------

Different parameters for adding files to staging area  :

1. git add -A or git add --all (Default): adding all files from leading directory into staging area
2. git add -A my_dir/ or git add my_dir/ : adding only files located in my_dir into staging area
3. git add -u : adding only modified files into staging area
4. git add -u my_dir/ : adding only updated files located in my_dir into staging area
5. git add . : adding all files in current directory into staging area
6. git add .gitignore : Add only specific file into staging area.

Difference between git add -A and git add . : git add -a add all files in leading directory and git add . only add files from current directory.

-----------------------------------------------------------------------------------------------------------------

Switch to branch without commiting

git stash save "worked on save function" : It will save this branch at this point without commited. And this branch at initial stage.
git stash list : List all stashes here
stash@{0} : On add : worked on save function
git stash apply stash@{0} : Come to our point back using this command. stash will not be dropped.
git stash pop : Come to our point back & drop stash from list.
git stash drop stash@{0} : drop stash@{0}
git stash clear : Clear all stash in list

If we want to do changes from one branch to another branch, then this is most wanted method.

Suppose, I have changed code in master branch.  But I want it to CalC branch. Then,
git stash save "add function" :  save stash on master branch
git checkout CalC :  Switched to CalC branch
git stash pop : apply changes
git add . : add files to staging area
git commit -m "intr" : commit & push


Note : New stash come at top position. Always at 0th position. @{0}.

-----------------------------------------------------------------------------------------------------------------

Git difftool & mergetool

git diff : It shows modification with red(Previous) and green(Current) colour content between previous and current file on terminal window. It is very hard to see where we have changed or what word we have changed. Because git diff shows full line instead of changed word.

So instead of using, there are many diff tool and merge tool available. I,e DiffMerge
Using this tool, we can easily find changes and solve if any conflicts are there just because it is graphically represent instead of just terminal.
For that we have to download and install that tool and configuration with our git. After configuration, check configuration using git config --global --list

Check
diff.tool = diffmerge
merge.tool = diffmerge

happened or not?

Now,
to run that diff tool ,
git difftool : It required permission to open diff tool, press Y to open difftool, and we can see modification clearly with color and word by word.

We can take changes according to we required by simply click on which changes and from which file(previous or current).

git mergetool : To merge branch. If any conflict occur, we can easily solve using this type tool due to visual representation.



-----------------------------------------------------------------------------------------------------------------

To change last commit message,
git commit --amend -m "new message" : It will change message of last commit message.

Hight thank full to Corey Schafer

I took help from following videos  :

1. Git Tutorial for Beginners: Command-Line Fundamentals
2. Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
3. Git Tutorial: Using the Stash Command
4. Git Tutorial: Diff and Merge Tools
5. Git Tutorial: Change DiffMerge Font-Size on Mac OSX
6. Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"

If you have any doubts for git, please comment on this blog. 



How to call segue programmatic?

Ans : 

For segue first, We have to set identifier in Class Inspector right side in XCode. Through that identifier, we can call like

performSegue(withIdentifier: "identifier", sender: nil) 

What is Content Hugging and Content Compression Resistance Priority?

Ans : 

The priority really come in to play only if two different constraints conflict. The system will give importance to the one with higher priority. So, Priority is the tie-breaker in the autolayout world.

1. Content Hugging Priority : 

Larger the content hugging priority , the views bound will hug to the intrinsic content more tightly preventing the view to grow beyond its intrinsic content size. Setting a larger value to this priority indicates that we don’t want the view to grow larger than its content.


In above example, we set both label leading, trailing, top and bottom but not set width constraint. So here conflicts will occur. You can see red line between two label showing conflict.

Solution : If we have label's content hugging priority higher than there will be no conflicts as hight priority label will not grow its size more than its content size. See below image :

Blue label has more content hugging priority (251) than green label(250). Blue label's width will be set fixed as its content size.

2. Content Compression Resistance : 

Setting a higher value means that we don’t want the view to shrink smaller than the intrinsic content size. It's simple : Higher the priority means larger the resistance to get shrunk.

Example . One button having large name and auto layout is set on button as its width is become 40. So, button's content is not readable. See image :
Button horizontal compression resistance is 750 and width constraint priority is 1000.

For Solution, let's change horizontal compression resistance to 1000 and width constraint priority less than 1000 i.e 999 . Now see effect on below image :
Button horizontal compression resistance is 1000 and width constraint priority is 999.


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

What is closure? Why we use closure instead of function sometime?

Ans : 

The two most used cases are completion blocks and higher order functions in Swift. 

Completion blocks: for example, when you have some time consuming task, you want to be notified when that task is finished. You can use closures for that, instead of a delegate (or many other things)


func longAction(completion: () -> ()) {
    for index in veryLargeArray {
        // do something with veryLargeArray, which is extremely time-consuming
    }
    completion() // notify the caller that the longAction is finished
}

//Or asynch version
func longAction(completion: () -> ()) {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        
        for elem in veryLargeArray {
            // do something with veryLargeArray, which is extremely time-consuming
        }
        dispatch_async(dispatch_get_main_queue(), {
            completion() // notify the caller that the longAction is finished
        })
    }
}

longAction { print("work done") }

In the example above, when you have a time consuming task, you want to know when the for loop finishes iterating through the very large array. You put the closure { println("work done") } as an input parameter for the function which will be executed after the for loop finishes its work, and print "work done". And what happened is that you gave a function (closure) to longAction and name it to completion, and that function will be executed when you call completion in longAction.

Sorted method works using closure.

About how sorted (probably) works: So the idea is, that sorted will go through the array, and compare two consecutive elements (i, i + 1) with each other, and swap them, if needed. What does it mean "if needed"? You provided the closure { (s1: String, s2: String) -> Bool in return s1 > s2 }, which will return true if s1 is greater than s2. And if that closure returned true, the sorted algorithm will swap those two elements, and continues this with the next two elements (i + 1, i + 2, if the end of the array is not reached). So basically you have to provide a closure for sorted which will tell "when" to swap to elements.

Understand Closure


Differences between internal testers and external testers in test-flight?

Ans : 

Both internal and external testers will install your app from the TestFlight app. Once invited, they will be sent an email asking them to install the TestFlight app. Once they have done so, they'll be able to install your beta app...
Internal Testers: Think of these users as employees who receive instant updates to your app without approval/review
  • Must be added manually via iTC
  • 25 Max allowed
  • Once your app is uploaded it's available immediately for internal testers (before it has been reviewed)
  • All internal testers must be added as a user in your iTC "Users and Roles" settings, which gives them certain permissions (review other answers and the docs for this). You wouldn't want to give just anyone permissions here.
  • Do not have a 60-day time limit
External Testers
  • Will only be able to use your uploaded build for up to 60 days. If you add additional builds, they can update, and the 60 days starts over again.
  • Will be able to test your app after
    1. You have submitted it for review
    2. It gets approved in TestFlight review and
    3. You set it to be available for testing. The review process us usually instant for new builds with the same version number. If you add a new version number, the review process can take up to 48hrs as of 10/2016.
  • Up to 2000 email addresses can be added. Each email address will allow a user to install the app on multiple devices. The email addresses do not need to match their Apple IDs.
  • They receive an invite to install your app once your first build is available for testing. If you add a new user after making a build available for testing, they'll immediately receive an invite. All users will receive notifications to install newer versions of the app if you upload additional builds.
  • Will be disallowed from using your app after you have pushed it to the official app store (which promptly ends the beta) or 60 days have passed since you started the beta, whichever comes first. If you end the beta without launching in the app store, and they try to open it, it will crash. Yay, Apple UX! If you do push a version to the app store with the same bundleName, version, and bundleID (build number doesn't matter), then your beta testers will automatically receive the app-store version of the app when it goes live.