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.

Make your iOS apps more secure with SSL pinning

SSL/Certificate pinning plays a very critical role in building highly secure mobile apps which users will be able to use even in countless insecure wireless network connections.

At a glance, Idea is the SSL(Secure Socket Layer) ensures the encrypted client-server communication over HTTPS. The encryption is based on PKI (Public Key Infrastructure) and a session key. The session key was introduced because encrypting and decrypting a public/private key uses a lot of processing time/power/space for sure it will slow down the process.

MIMT, Yes SSL Communication is very secure but the man-in-the-middle attack still poses an exact threat using ARP cache poisoning and DNS spoofing.

SSL/Certificate Pinning, ensure that the app communicates only with the designated server only and the prerequisites for SSL pinning is saving the target’s server SSL certificate within the app bundle.

SSL pinning is implemented within the

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void

and here are the steps we need to follow.

  • First read the server trust and server certificate.

let serverTrust = challenge.protectionSpace.serverTrust
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0

  • Now set the policies for server validation, previous failure count etc.

SecTrustSetPolicies(serverTrust, SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))

  • Start policies validation, convert server certificate in Data and get the local certificate from bundle.

 let remoteCertificateData = SecCertificateCopyData(certificate)
 let pathToCert = Bundle.main.path(forResource: “certificate”, ofType: “cer”

At last compare your policies result and local certificate data with your server certificate data, if everything goes well complete the challange with credentail.

completionHandler(.UseCredential, credential)

Otherwise cancel the authentication and pass nil as credentails.

completionHandler(.CancelAuthenticationChallenge, nil)

Thank you reading, you can download the source code from GIT and also learn contribute about iOS Security.

Swift Code Snippets | Save Developer Hours

Do you write hundreds lines of code everyday ? And would you like to save ? Well than, code snippet libray may help you here.

The Concept of code snippets is saving a piece of code which we write very often. so now we can save it as snippet and use it quickly with shortcuts or drag & drop.

Here it is in IDE.

Screen Shot 2017-05-30 at 9.11.33 PM.png

How to build A Custom Snippet ?

By default, Xcode provides serval snippets and let add our own.

  1. Select the code which you want to create as snippet.
  2. Just drag and drop inside the Snippet option.

ima.png

we can also Edit Custom Snippet, Give the title and summary to our snippet, Completion Shortcut is what i like most its just give short name, define the scope, if its no longer required just select and delete it.

 

 

 

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.