Reputation: 743
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.
Upvotes: 5
Views: 5354
Reputation: 636
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
}
Upvotes: 7