Safety In Swift | Fun Time

Let’s say we have a Car and we want it to be safe so we have seatbelts and airbags and we don’t want to let the truck drive unless safety points passed.

Code Sample

enum Safety {
    case seat
    case door
    case airbag
}

struct Car {
    var seatBeltEnabled: Bool
    var doorLocked: Bool
    var airBagsWorking: Bool
}

extension Car   {
    func drive() throws {
        guard seatBeltEnabled else {
            throw Safety.seat
        }

        guard doorLocked else {
            throw Safety.door
        }

        guard airBagsWorking else {
            throw Safety.airbag
        }
        //Everything fine.... drive carefully
    }
}

I hope everything is looking fine so that’s the beauty of Swift otherwise in other approaches we need to manage it with if-else before we start driving.
That’s all about the small beautiful thing I learned today.

How to Respond to an Authentication Challenge | iOS

How to Respond to an Authentication Challenge

If a session requires authentication it creates authentication challenge

 URLSession:task:didReceiveChallenge:completionHandler: 

in order for the connection to continue, the delegate has three options.

  • Provide authentication credentials
  • Attempt to continue without credentails
  • Cancel the authentication request.

NSURLProtectionSpace will give all information about the authentication type and failure if any attempts failed earlier.

Providing Credentials

To attempt to authenticate, the application should create an NSURLCredential object with authentication information of the form expected by the server. You can determine the server’s authentication method by calling authenticationMethod on the protection space.

  • HTTP basic authentication (NSURLAuthenticationMethodHTTPBasic) requires a user name and password. P
  • HTTP digest authentication (NSURLAuthenticationMethodHTTPDigest), like basic authentication, requires a user name and password.withcredentialWithUser:password:persistence:.
  • Client certificate authentication (NSURLAuthenticationMethodClientCertificate) requires the system identity and all certificates needed to authenticate with the server. Create an NSURLCredential object.
  • Server trust authentication (NSURLAuthenticationMethodServerTrust) requires a trust provided by the protection space of the authentication challenge.

Continuing Without Credentials

If the delegate chooses not to provide a credential for the authentication challenge, it can attempt to continue without one.

NSURLSessionAuthChallengePerformDefaultHandling processes the request as though the delegate did not provide a delegate method to handle the challenge.

  • NSURLSessionAuthChallengeRejectProtectionSpace rejects the challenge. Depending on the authentication types allowed by the server’s response, the URL loading class may call this delegate method more than once, for additional protection spaces.

Canceling the Connection

The delegate may also choose to cancel the authentication challenge, by passing NSURLSessionAuthChallengeCancelAuthenticationChallenge to the provided completion handler block.

Dependency Injection | Swift | Quick Note

A short answer is, it’s scary terms for a very simple idea!!! See this lines of code.

class Engine {

}

class Car {
    let engine: Engine? = nil
    init() {
        self.engine = Engine()
    }
}

we are creating dependency internally but the object can be also received from outside with lots of benefits like the object become instantly testable, Testing becomes possible without any frameworks, No runtime effects, This makes the whole system more loosely coupled.

class Car {
    let engine: Engine? = nil
    init(engine: Engine) {
        self.engine = engine
    }
}

There are three common types of dependency injections.

Setter, Interface, Constructor based.

In iOS Constructor based is preferable one, it’s when dependency passed to the client in the initializer and don’t change during the whole client life and the biggest advantage of this type could be that it makes the violation of the single responsibility programming principle, if an object takes all dependencies in the initializer and if it has more than three parameters so it means refactoring is needed.

Thanks for reading!!!

Swift | iOS 10 | Orientation | Quick Notes

When it comes to handling Orientation in iOS App Development, creates little confusion because with every release their minor changes. so let’s see who does it works with iOS 10.

First thing if you want to support all Orientations just enable it from here.

Screen Shot 2017-08-02 at 3.40.51 PM.png

Second, if the requirement is something like, need Orientation support only for few Controllers. make sure you have followed the first case and just this code snippet for enabling/disable it for each view.

override var shouldAutorotate: Bool {
    return true
}

its simple as its looking just return `true` if you want to support orientation for controller else return `false`. Next concern is if you are returning true then you have an option to specify the orientations as well just implement this code snippet.

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.all
} 

Click `UIInterfaceOrientationMask` to see the options so just return whatever you want to use. Sounds good?

public struct UIInterfaceOrientationMask : OptionSet {
    public init(rawValue: UInt)
    public static var portrait: UIInterfaceOrientationMask { get }
    public static var landscapeLeft: UIInterfaceOrientationMask { get }
    public static var landscapeRight: UIInterfaceOrientationMask { get }
    public static var portraitUpsideDown: UIInterfaceOrientationMask { get }
    public static var landscape: UIInterfaceOrientationMask { get }
    public static var all: UIInterfaceOrientationMask { get }
    public static var allButUpsideDown: UIInterfaceOrientationMask { get }
}

Thank you for reading.

Swift | No Main Method | No Entry Point | iOS App

That is interesting to see, there is no main() for Swift iOS project.

Because Cocoa Touch uses the @UIApplicationMain attribute (for Cocoa its @NSApplicationMain) to indicate that it is the application delegate, Using this attribute is equivalent to calling UIApplicationMain function and passing the class name of the delegate class.

If you do not use this attribute, than supply a main.swift file with code at top level that calls the UIApplicationMain(_:_:_:_:) it means if you app uses custom subclass of UIApplication as its principle class, call the UIApplicationMain(_:_:_:_:) function instead of using this attribute.

Objective C Days | Memory Management |Short Note to Brush up

Summary

Let’s see the traditional C ways for clearing up of unused objects is a bit of a nightmare. There are no ways in the language like how should be approached.

Imagine one function A create one object and pass it to another function B now both are using the same data now the problem is who is: the responsible for deleting it if it no longer used? and let’s say we have one function who is also gonna use the same data than what?

The solution is there are conventions and design patterns to handle these situations,  that’s the reason the reference counting was developed and management technique used in Obj-C.

What we have in Obj-C

Obj-C uses reference counting as its Memory Management Technique so according to that each object keeps an internal count of how many times it’s needed.  So only in case of, if count drops to zero. Yes you can compare it with Garbage Collector we have in Java but it’s not like automatic some chunk of code getting executed and removing the objects which ones are not needed.

Ownership

Most important thing is Object Ownership it means an object owner is someone that has explicitly said: “I need that object, don’t delete”. So one object can have more than one owner.

If object owner is not using it they have the responsibility to tell so that the reference count should be decreased by one. So while dealing with Obj-C pointers/Objects it’s really good to send correct messages.

Messages

alloc, it will allocate a fresh instance of the object, set the reference count +1.

new, shortest way to write alloc&init.

retain, you passed the object and you want to tell you to need that so its reference count should be increased by 1 again.

autorelease, need object temporarily and want to delete once you did with the operations.

copy creates a new copy of the object.

dealloc, opposite of init method, automatically get called right before the object is destroyed.

 Convenience Methods

Static methods used for allocating the initializing objects directly but are aware that you are not the owner of that object, once the scope of your program finish it will be removed.  Ex: [NSString stringWithFormat:@”Say %@”,@”Hello”];

Autorelease Pools

It’s an instance of NSAutoreleasePool, objects which are to be auto released. You can also send a message to autorelease or create object using convenience methods. So once the object added into autorelease pool and when the pool is popped, all the objects will be deleted.

Retain Cycles

Retain cycle is a condition where two objects strongly maintain a reference to each other and stop each other from being released. For example, let we have two classes as.

@interface Parent : NSObject
@property (nonatomic, strong) Child *child;
@end

@implementation Parent
@end

@interface Child : NSObject
@property (nonatomic, strong) Parent * parent;
@end

@implementation Child
@end

So, at some point of time when creating object of any of these class as

Parent *parent = [[Parent alloc] init];
Child *child = [[Child alloc] init];
parent.child = child;
child.parent = parent;

Here the parent object maintaining a strong reference of Child class and child object maintaining a strong reference of Parent class in back. So, both parent and child object having a reference count of one and one. Both objects will get released from memory only when their reference count will reach to zero but in this scenario, this will not be going to happen ever because both are mutually pointing to each other a dead lock is get created here. This situation is called the Retain Cycle that will lead to memory leaks.

Fortunately, it’s very easy to fix this problem—just tell one of the properties to maintain a weak reference to the other object so, what’s this weak and strong reference means??

Strong Reference: A strong reference says that don’t release this object till I m owning this.

Weak Reference: A weak reference says that don’t release this object until someone else pointing this strongly.

Just like strong and __strong, weak and __weak keywords are there for declaring properties and instance variables respectively as a weakly referenced object.

Quick Tips and common mistakes

Think about strong and weak pointers as well as retain cycles, Avoid unnecessary caching, Don’t declare every object  globally unnecessarily, use Xcode Instruments such as static analyzer and find the potential memory leaks and fix them

Arrays, Dictionaries and other objects that contain any object generally retain objects once you add it to them. It means once you create an object the reference count will be 1 and once you add it into an Arrays it will be 2.

Releasing the Object that you don’t own, let’s say if creating a new object using convenience method than there is no need to release that.

Keeping and using an Object that you don’t Own.

Calling dealloc directly. So never call dealloc by the way you have to call init after calling alloc its kinda default constructor for init the default value of the object.

Over-releasing. Accidentally you’re releasing something twice instead of once. You can also track these crashes by just enabling Zombies.

Retain Cycles. When an object released there is a cascading effect, the root object released its children’s as well and so on. Let’s say there is some condition like A owns B and B owns An as they own each other.

iOS Concurrency | Introduction | Options

Concurrency is two sided-weapon, that you should master and learn how to use because it will help you to write efficient code with fast execution but if you are misusing it, then results will be poor app performance, crashes etc.

So before writing code think about the problem, why do we need that and which API do you need to resolve it.

In iOS, we have different APIs that we can be used. But wait here the question is why do we need Concurrency?

  • Utilize iOS Hardware: Now all of the iOS devices are with multi-core processors that allow developers to execute multiple tasks parallel. So here we can earn lots of benefits.
  • Better User Experience: Code for call multiple web services, handle IO and some heavy tasks etc will freeze UI and make your app nonresponsive so if as a user I face this I will close the app for sure, but with concurrency, all tasks can be done in the background without hanging the main thread.
  • APIs like NSOperation and Dispatch Queues makes it really easy: Earlier creating and managing threads is not easy that’s the reason everyone gets scared when they hear about concurrency. Another major advantage of APIs is, it will also help you to manage synchronization to avoid the race condition, it happens with two threads try to access the shared resource.

Properties | Swift | iOS | Stored

Properties associate value with a paticular class, structure or enumeration. Stored Properties (provided by class, struct and enum) store constant and variable values as part of instance, whereas Computed Properties (provided by class and struct only) calculate a value. Properties can also be associated with type itself its called Type Properties. Apart from that we can add observers to monitor the changes in a property’s value there you can response to your custom actions, we can add it to Stored Properties and also property that a subclass.

Stored Properties

Simplest form, its a constant or variable that is stored as a part of an instance of a particuler class, struct or enum.

struct Box  {
    var height  : Int
    let width   : Int
}

var box1 = Box(height: 101, width: 10)

It can be either Variable stored property (introduced by var) or Constant stored property(introduced by let). if its Variable stored property than we can set initial value during initialization and if Constant stored property without default value than yes as well.

Lazy Stored Properties

Whose initial values is not calculated until the first time it is used. they are useful when the initial value for a property is dependent on other factors or sometime if the initial value for a property requires complex or computationally expensive setup that should not be performed unless it is needed.

class DataImporter  {
    /*
     This class is responsible for fetching and holding the file data.
    */
    var fileName = "data.json"
}

class DataManager   {
    var data = [String]()
    lazy var importer = DataImporter()
}

let dManager = DataManager()
dManager.data.append("One")
dManager.data.append("two")

Now here the interseting part is till now importer property is not created. because is marked as lazy so the property is only created when the importer property is first accessed.

 

Subscripts in Swift ?

Shortest way to access the member elements of collection, list or sequence, means there is no need to create saparate function. lets say you have an array so you can write subscripts for setting and retrieving the value by index. Sounds good ???

Another good thing is we can define number of subscripts based on the type of index value we pass, even we can define subscripts with multiple input parameters, so its all to our need.

The syntax is very much similar to stored property and functions. Just we need to write subscript keyword and specify one or more input paramters and reture type. like the methods subscripts are also read-write or readonly. This behaviour is communicated by the same way we do in computed properties. 

subscript(index: Int) -> Int    {
    get {
        //return value here
    } set(newValue) {
        //set the new value here
    }
}

the usage is to access the member elements in a collection, list or sequence. For example, Swift’s Dictionary instance. You can set and get the value using Key. if they key does’t exist it will add into the Dictionary.

var priorities = ["Work" : 3, "Family" : 1, "Other" : 4]
priorities["Work"] = 2

Swift’s Dictionary type implements its key-value subscripting, its takes and returns an optional value. if you set the value as nil it’ll remove from Dictionary.

priorities["Work"] = nil

the interseting part what i like is subscripts can take any types of values, n number of value and can return any type of value, but they can’t use in-out parameters and can’t provide default parameters value.

struct Matrix {
    let rows: Int, columns : Int
    var grid : [Double]

    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }

    private func isValidIndex(row: Int, column: Int) -> Bool    {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }  

    subscript (row: Int, column: Int) -> Double  {
        get {
            assert(isValidIndex(row: row, column: column))
            return grid[(row * column) + column]
        } set {
            assert(isValidIndex(row: row, column: column))
            grid[(row * column) + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[1, 1] = 10.0

print(matrix[1, 1])