5

I have a file that needed to be uploaded to a server and I have been told to separate the file into multiple chunks before uploading. So here is the question:

1) I have converted the file into "Data" type (bytes). How do I split it into chunks of 1MB each?
2) After splitting, how do I upload it using Alamofire? if not possible using Alamofire, pls recommend how do I do it.

I'm using swift 3 and Code 8.3. Any help is much appreciated.

Gavin Morrow
  • 711
  • 1
  • 6
  • 19
da32
  • 703
  • 1
  • 9
  • 18
  • Check SO here: https://stackoverflow.com/questions/19343053/how-to-work-with-large-file-uploads-in-ios and here https://stackoverflow.com/questions/19833223/upload-large-file-video-to-server-in-ios – Fabio Berger Sep 28 '17 at 08:17
  • @da32 Have you found solution for this? Now I'm looking for same requirement. – Subramani Dec 22 '22 at 10:44

1 Answers1

6

I think this may work

let path = Bundle.main.url(forResource: "test", withExtension: "png")!
    
do
{
    let data = try Data(contentsOf: path)
    let dataLen = (data as NSData).length
    let fullChunks = Int(dataLen / 1024) // 1 Kbyte
    let totalChunks = fullChunks + (dataLen % 1024 != 0 ? 1 : 0)
        
    var chunks:[Data] = [Data]()
    for chunkCounter in 0..<totalChunks
    {
        var chunk:Data
        let chunkBase = chunkCounter * 1024
        var diff = 1024
        if chunkCounter == totalChunks - 1
        {
            diff = dataLen - chunkBase
        }
            
        let range:Range<Data.Index> = chunkBase..<(chunkBase + diff)
        chunk = data.subdata(in: range)
            
        chunks.append(chunk)
    }
        
    // Send chunks as you want
    debugPrint(chunks)
}
catch
{
    // Handle error        
}
Gigi
  • 616
  • 6
  • 7
  • this one working fine in split of _nsdata_ to chunks of _nsdata_ – prateek sharma Jun 28 '18 at 08:40
  • 4
    It will crash on this line `let data = try Data(contentsOf: path)` in case of large file. But this approach is ok for small files. – Jamil Apr 25 '19 at 07:28
  • hi, i go error in this line: "let range:Range = Range(chunkBase..<(chunkBase + diff))" -> "'init(_:)' is unavailable: CountableRange is now a Range. No need to convert any more". Can you help? – famfamfam Jun 26 '20 at 03:25