How to add Certificate Pinning in iOS (Swift)

February 15, 2019

If you really want to secure your app, you can use a concept called Certificate Pinning which essentially you store your networking Certificates on the client side. By doing so, your app won't depend on the system "trusting" bad certificates and will not all Man in the Middle attacks. Use the following code below to do so:

        let serverTrustPolicy = ServerTrustPolicy
            .pinPublicKeys(publicKeys: ServerTrustPolicy.publicKeys(),
                           validateCertificateChain: true,
                           validateHost: true)
        let serverTrustPolicies = [
            "<YOUR DOMAIN (ie>": serverTrustPolicy
        #if DEBUG
        Alamofire.SessionManager(configuration: configuration)
        Alamofire.SessionManager(configuration: configuration,
            ServerTrustPolicyManager(policies: serverTrustPolicies))

Now all you need to do is save your certificate (Root Certificate preferred) anywhere in your project (publicKeys will search your whole project) and you'll be good to go.