-1

I'm working on Video upload process, need to upload large video as multiple chunks. Each chunks should be the size of 5 MB.

Please share the code for converting large video to multiple chunks under size of 5 MB each in swift. Any help is much appreciated

Mathew
  • 62
  • 7
  • Google is your friend and you are not the first who tried. Nobody is going to write the code for you. But maybe [this](https://developer.apple.com/forums/thread/89044) helps you. – LoVo Dec 22 '22 at 11:50
  • @LoVo Thank you, I understand but I've been searching code for this from last two days. Only I've found split by duration not by size basis. That's why I'm posting here. Thank you for your concern. – Mathew Dec 22 '22 at 11:55
  • 1
    Got you, but i would assume you wrote some code yourself already. I assume you could get more help if you would post your approach. Anyway, [here](https://stackoverflow.com/questions/44799133/ios-how-to-upload-a-video-with-uploadtask) is a post which should point you to the right direction. – LoVo Dec 22 '22 at 13:55

1 Answers1

1

Try this,

    let selectedSize = selectedVideoSizeInMB
    let seconds = durationInSeconds
    print("Size", selectedSize)
    print("Seconds", seconds)
    
    let splitDuration: Int = Int(seconds / (selectedSize/5))
    print("Split Duration", splitDuration)
    
    do {
        let data = try Data(contentsOf: videoUrl)
        let dataLen = data.count
        print("Data Size", data.count)
        let chunkSize = ((1024 * 1000) * 5) // MB
        print("Chunk Size", chunkSize)
        let fullChunks = Int(dataLen / chunkSize)
        let totalChunks = fullChunks + (dataLen % 1024 != 0 ? 1 : 0)
        print("Chunk count", totalChunks)
        
        var chunks:[Data] = [Data]()
        for chunkCounter in 0..<totalChunks {
            var chunk:Data
            let chunkBase = chunkCounter * chunkSize
            var diff = chunkSize
            if(chunkCounter == totalChunks - 1) {
                diff = dataLen - chunkBase
            }
            
            let range:Range<Data.Index> = chunkBase..<(chunkBase + diff)
            chunk = data.subdata(in: range)
            chunks.append(chunk)
            print("The size is \(chunk.count)")
        }
        self.chunksDataArray = chunks
        print("Total Chunk", chunks.count)
    }catch{
        return
    }
Subramani
  • 477
  • 2
  • 14