Saeed Rezaei

Nov 12, 2021

2 min read

Calculate MD5 checksum for video in iOS

In my current company, we work on an amazing photo-sharing app.

When we start improving some upload features, we faced an issue with calculating checksum for video files. if you try to pick a video from the photo library, with “UIImagePickerController”. you realized that the checksum of the video is always different. with this issue, the application can’t check the current file has already been uploaded or not.

We check some scenarios and finally, this solution fixed our problem.

After the user selects a video in “UIImagePickerController” this delegate called in the app

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])

  1. you should fetch “referenceURL” from the “info” object.

guard let url = info[.referenceURL] as? URL else { return }

2. then fetch asset with that “url”

let asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)

3. then request AVAsset with the “PHImageManager”

PHImageManager.default().requestAVAsset(forVideo: asset.firstObject!, options: requestvideo) { video, audioMix, info in .…. }

The “video” object is referencing the video file and if you calculate the checksum of the file, it returns the same every time 🎉.

the entire code

guard let url = info[.referenceURL] as? URL else { return }

let asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)

let requestvideo = PHVideoRequestOptions()

PHImageManager.default().requestAVAsset(forVideo: asset.firstObject!, options: requestvideo) { video, audioMix, info in

if let newVideo = video as? AVURLAsset {

// calcuate mdf(newVideo)

}

}