Tutorials

Uploading a Large file using Alamofire 5

Very large files can not be converted into data at once and moved around in variables. It is simply not possible as very large files could trigger memory warning and eventual crash. Now the question arises how do we upload very large files using Alamofire? Solution is simple just pass the file url to alamofire and it will upload it in chunks. As shown in code below

        let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")

        AF.upload(multipartFormData: { (multipartdata) in
// add any additional parameters first
        //multipartdata.append(<data>, withName: <Param Name>)
            multipartdata.append(fileURL, withName: <Param Name>)
        }, to: "https://httpbin.org/post").responseJSON { (data) in
            print(data)
        }

Uploading a file this way does not require you to move a very large file at once in you memory.This strategy might be over kill for uploading images for which you might be able to convert them to data at once as shown below

 let image = UIImage.init(named: "myImage")
 let imgData = UIImageJPEGRepresentation(image!, 0.2)!
AF.upload(imgData, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
    debugPrint(response)
}

Read More

Camera and UIImagePickerController to take photos with swift

You can easily integrate camera functionality in your application using UIImagePickerController which is built-in UIKit. It requires very few steps to do so. I am providing the basic steps below

Make your viewcontroller calss conform to UIImagePickerControllerDelegate and UINavigationControllerDelegate

//
//  ImagePickerViewController.swift
//  ImagePicker
//
//  Created by amarendra on 20/06/20.
//  Copyright © 2020 amarendra. All rights reserved.
//

import UIKit

class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

Add extention to your viewcontroller

extension ImagePickerViewController{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.editedImage] as? UIImage else {
               print("Error picking image")
               return
           }
        //use your image
        
    }
}

Your code is almost done. Now add some button or function from where you will launch picker. And present your picker

@IBAction func cameraTapped(_ sender: UIButton) {
  //launch camera
        let cameraView = UIImagePickerController()
        cameraView.sourceType = .camera
        cameraView.allowsEditing = true
        cameraView.delegate = self
        present(cameraView, animated: true)
}

Now when you will click on the camera button it will call the cameraTapped function which in turn will launch the native camera . NOTE: in order to test on simulator set

    cameraView.sourceType = .photoLibrary

Thanks for reading. Comment if you face any issue

Read More

SSL Pinning for preventing Man in Middle Attack

Communicating with a server gives an entirely new dimension to an application and can do a huge amount of value addition for both client and business. But communication with server also comes with its share of risks.

A insecure connection is really a bad idea but a poorly implemented https connection is even worse.

In order to make sure that even on ssl your app is communicating with the server it is intended to and not a imposter, you should implement SSL PINNING.

What is SSL Pinning in iOS APPS ?

SSL pinning simply means that the application has a pinned SSL certificate with it. Every update of the certificate requires each installed app to update its copy. This can be achieved through a new app version. SSL pining works in the following steps

  • A copy of certificate is kept with in the app bundle
  • Every time when the a secure connection is initiated app compares its copy of certificate with server certificate
  • If they don't match the connection is terminated

How to acheive SSL Pinning in swift application?

It is really simple you just need to compare app's local copy of the certificate with the server copy in URLSessionDelegate

class URLSessionPinningDelegate:NSObject, URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            if let serverTrust = challenge.protectionSpace.serverTrust {
                let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
                if(isServerTrusted) {
//Getting server certificate
                    if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                        let serverCertificateData = SecCertificateCopyData(serverCertificate)
                        let data = CFDataGetBytePtr(serverCertificateData);
                        let size = CFDataGetLength(serverCertificateData);
                        let cert1 = NSData(bytes: data, length: size)
//Getting local certificate
                        let file_der = Bundle.main.path(forResource: "<YOU CERTIFICATE>", ofType: "der")
//Comaprign both
                        if let file = file_der {
                            if let cert2 = NSData(contentsOfFile: file) {
                                if cert1.isEqual(to: cert2 as Data) {
                                    completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
                                    return
                                }
                            }
                        }
                    }
                }
            }
        }

        // Certificates dont  Match
        completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
    }

}
 

That was it!!! so simple.

Read More

A pat on the back !!

NEED A JOB? NEED TO HIRE? NEED HELP?

Join group of Software Professionals

iOS DEVELOPER’S DEN

×