Stevik
Stevik

Reputation: 1152

iOS Swift - Cutting video to multiple parts

I'm working on an app that uploads a recorded video on a server, but it has to be sent in multiple parts which are encoded to base64.

How can I split/cut a video to multiple parts using swift ?

Upvotes: 1

Views: 2200

Answers (1)

Nimit Parekh
Nimit Parekh

Reputation: 16864

First of all convert into NSData then divide the that data into different different chunks and then that chunk encodeusing base64 that send to server side.

Now, Following is the sample code for same.

import UIKit
import MobileCoreServices
import Foundation

extension String {
    var ns: NSString {
        return self as NSString
    }
    var pathExtension: String? {
        return ns.pathExtension
    }
    var lastPathComponent: String? {
        return ns.lastPathComponent
    }
}

// MARK: - Mixed string utils and helpers
extension String {


    /**
     Encode a String to Base64

     :returns:
     */
    func toBase64()->String{

        let data = self.dataUsingEncoding(NSUTF8StringEncoding)

        return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    }
}

class ViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var img:UIImageView!=nil

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()    
    }

    @IBAction func buttonTapped()
    {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            //            print("Camera Available")
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            imagePicker.allowsEditing = false
            imagePicker.mediaTypes = [kUTTypeMovie as String]
            self.presentViewController(imagePicker, animated: true, completion: nil)
        }
    }


    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
         dismissViewControllerAnimated(true, completion: nil)

        let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL!
        let pathString = videoUrl.relativePath
        print(pathString)

        let videoDataURL = info[UIImagePickerControllerMediaURL] as! NSURL!
        let videoFileURLs = videoDataURL.filePathURL

        let chunkSize : Int = 2*1024*1024 // 2 MB
        do {
            let videoData =  try NSData(contentsOfURL: videoFileURLs!, options: .DataReadingMappedIfSafe)
            var newFileName = pathString!.pathExtension
            let totalSizeOfBase64 : Int = Int(videoData.length)
            for var chunksWritten :Int = 0; chunksWritten * chunkSize < totalSizeOfBase64; chunksWritten++
            {
                let modifiedURLString = NSString(format:" %03lu.MOV", chunksWritten) as String
                newFileName = newFileName!+modifiedURLString

                let rangeValue  = NSMakeRange(chunksWritten * chunkSize, min(chunkSize, totalSizeOfBase64 - chunksWritten * chunkSize))
                let finalString  = videoData.subdataWithRange(rangeValue)

                //Encoding Base64
                let base64String = finalString.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

                print("\(base64String)")
//                print("\(newFileName)")
                newFileName = pathString!.pathExtension
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

May this helps lot.

Upvotes: 2

Related Questions