Written by Sean Behan on Sat Sep 15th 2018

How to Chunk Large Files in Swift (4.1)

It takes a bit of work but this is the solution I found that finally worked, thanks to this Stack Overflow thread https://stackoverflow.com/questions/46464177/split-data-in-chunks-and-upload-to-server

The example below was written for an XCode Command Line Application project template. However, it should work fine for iOS and MacOS apps. The main thing is that the file url is just hard coded. With an actual application you will need the url of the asset from FileManager or UIImagePickerController, for example.

In the example below I am chunking the file into ~4MB parts.

import Foundation

let data = try Data(contentsOf: URL(fileURLWithPath: "path/to/large/file.jpg"))
let dataLen = data.count
let chunkSize = ((1024 * 1000) * 4) // MB
let fullChunks = Int(dataLen / chunkSize) 
let totalChunks = fullChunks + (dataLen % 1024 != 0 ? 1 : 0)

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> = Range<Data.Index>(chunkBase..<(chunkBase + diff))
  chunk = data.subdata(in: range)
  print("The size is \(chunk.count)")
}

That is it!

In a later post I will show how to combine this with Alamofire to accomplish asyncronous multi part file uploads.


Tagged with..
#swift #ios #macos #apple #files #chunks #nsdata

Just finishing up brewing up some fresh ground comments...