Tuesday, 26 April 2016

3D touch(Peek and Pop)

With the new latest iOS 9 update now we can use the 3D touch that can provide more flexibility to a user. One of them is the peek and pop feature to view the preview of the controller before opening it. Today we will learn how to implement it in our iOS apps. 

Before beginning let us first understand what is peek and pop.
   Peek – To display the preview is called as peek.
   Pop – Navigation to the view that is currently shown as preview is  called as pop.


Let us first create a simple view controller project with the navigation controller. Now create a another controller that will show as a preview.
Now to implement peek and  pop, first step is to register the view that will be source. In our demo we will use table view as a source view.

if traitCollection.forceTouchCapability == UIForceTouchCapability.Available {
            registerForPreviewingWithDelegate(self, sourceView: self.tblPeekPop 
}

Note – Before registering source view make sure that device supports the 3D touch.
 
Now the next step is to conforms the UIViewControllerPreviewingDelegate. Let’s implement the delegate that are required for peek and pop.

func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {

        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
        let objPreviewView = storyboard.instantiateViewControllerWithIdentifier("PreviewViewController") as? PreviewViewController 
      /*objPreviewView!.preferredContentSize = CGSize(width: 0.0, height:180.0) */
      return objPreviewView
}    

In the above delegate method create a view controller that will show as a peek view. Here we can set the content size of the preview controller that will display the preview view of that height.

After preview when use force touch on the preview view then we have to navigate it to the view controller to display it in full screen.(Pop)

    func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit :UIViewController) {     
     showViewController(viewControllerToCommit, sender: self)
}

Here we will show the view controller that we have created to push in the navigation. Now user will move to the next view controller.

That’s all we have successfully integrated it.

Here is sample project with all the code of the above tutorial.

If you face any issue or have any suggestions, please leave your comment.








Saturday, 23 April 2016

Singleton in swift (Best way to create)

There are many approaches to create a singleton object. In Objective C we create a singleton object by using dispatch_once.

+(id)sharedInstance {
    static Shared *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });
    return shared;
}

Here dispatch_once method of GCD ensures that object is created only one time and also it is thread safe.

In swift  we can also use the same approach to create a singleton object but today we will learn the best approach to create it. The best approach is Swift is one line singleton.

class Shared: NSObject {

    static let sharedInstance = Shared()
    private override init() { }
}

You were thinking how only writing one line solves our problem. So the answer is when the lazy initialization of the static variable is created then it is initiated inside the dispatch_once block and that is thread safe and ensures that only one instance is created.



You can easily check that by applying the breakpoint and checking the queue. Here you can easily see that internally it is calling dispatch_once.

Note – Don’t forget to make the init as private as it will ensure that no object can be created outside. If anyone try to create the object of your shared class then it will gives you error.


That’s all, enjoy creating you singleton object.

If you face any issue or have any suggestions, please leave your comment.

Tuesday, 19 April 2016

What’s new in Swift 2.2

Swift 2.2 brings new syntax, new features, and some deprecations too. Today we will learn all the new changes that are made in swift 2.2.

As a reminder, “deprecation” means that a function or language feature is no longer recommended for use and will be removed entirely at a later date. In practice that means Swift will issue a compiler warning today, and a compiler error in the future — likely Swift 3.

 

Compile-time Swift version checks


Swift 2.2 introduces a new compiler directive that makes cross-version compatibility check. Now you can specify blocks of code that should be read only if the compiler supports a specific Swift language version.

#if swift(>=2.2)
         print("Swift with higher version")
#else
         print("Swift will less version")
#endif

Compile-time Selector checks

Right now if we are using the selectors and call the method that does not exsits the at compile time we will not get any error but at runtime we will face the crash

let button = UIButton()
button.addTarget(self, action: "buttonClicked", forControlEvents: UIControlEvents.TouchUpInside)

If we write the method name buttonClick by mistake, then Xcode will not notify us and will crash when button is clicked.

Using #selector will check your code at compile time to make sure the method you want to call actually exists. If the method doesn’t exist, you’ll get a compile error.

button.addTarget(self, action: #selector(buttonClick) , forControlEvents: UIControlEvents.TouchUpInside)

It will give you error “Use of unresolved identifier ‘buttonClick’”.



Built-in Tuple comparison

Swift 2.2 introduces the ability to compare two tuples for equality, which means it will check each element in one tuple against the matching element in another, and report true if all elements match.

let oldSwift = ("Swift", "2.2")
let newSwift = ("Swift", "2.2")

if oldSwift == newSwift {
           print("Tuple matched")
} else {
print("Tuple not matched")
}
It will give the output as “Tuple matched”.

C- Style Loops are Deprecated

With Swift 2.2 now you can not use C style loop.
for var i = 0; i < 5; i++ {
           print(i)
}
Now with the new swift 2.2 you can use the loop like.
for i in 0 ..< 5 {
           print(i)
}
If you want to use a reverse range then you can not directly reverse the range like below code.
for i in 5...0 {
           print(i)
}
It will give you crash at runtime. You have to use the reverse function to make the range in reverse order.
for i in (0...5).reverse() {
           print(i)
}

++ and -- are deprecated

Both prefix and post fix operators are now disabled. Now you can not use ++ and --.
You will instead need to use i += 1 or i -= 1.

var parameters are deprecated

Prior to Swift 2.2 we can declare function parameter as var if we want to modify it inside the function. With new var parameter depreciation we will not be confused between inout and var parameter as both can be modified inside function and that can create confusion.
func checkVarChanges(var str: String) {
           str = str.lowercaseString
           print("\(str)")
}
Now with Swift 2.2.
func checkVarChanges(str: String) {
           let lowerCase = str.lowercaseString
           print("\(lowerCase)")
}
More keywords can be used as argument labels
 
Swift has lots of keywords that you can use as a arguments but right now you have to place it in backticks like this.
func executeFunction(str: String, `repeat` count: Int) {
        print(str)
 }
 executeFunction("name", `repeat`: 4)

But now in swift 2.2 we can use any keyword except  inout, var, let. Now with swift 2.2 code will be written as.
func executeFunction(str: String, repeat count: Int) {
        print(str)
 }
executeFunction("name", repeat: 4)
Renamed debug identifiers: #line, #function, #file

Currently we are using  __FILE__, __LINE__, __COLUMN__, and __FUNCTION__ for debugging like printing line number,function and so on. Now in Swift 2.2 they are replaced by #file, #line, #column and #function.

func checkMyFunctionNameAtLine() {
//old - deprecated statement
           print("This is on line \(__LINE__) of \(__FUNCTION__)")

//new - change in swift 2.2
           print("This is on line \(#line) of \(#function)")
}