Reputation: 4171
When we try to upload a large file (Chunk Wise) in Azure Blob, we get a high memory usage issue in iOS. Below code has been used to upload a large file (Chunk Wise) in Azure Blob.
func uploadToBlob(_ url: URL) {
let blobClient = self.account?.getBlobClient()
let blobContainer = blobClient?.containerReference(fromName: Configure.shared.blobName!)
let blobBlock = blobContainer?.directoryReference(fromName: blobFolder).subdirectoryReference(fromName: directory).subdirectoryReference(fromName: subDirectory).blockBlobReference(fromName: Date().toUploadFormate+"_"+orgUrl.lastPathComponent)
let data = NSData(contentsOf: url)!
let length = data.length
let chunkSize = 4194304
var offset = 0
var blockList : [AZSBlockListItem] = []
func nextChunk() {
let thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset
let chunk = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: data.bytes+offset), count: thisChunkSize, deallocator: .none)
offset += thisChunkSize
let utf8str = UUID().uuidString.data(using: .utf8)
if let base64EncodedId = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) {
blockList.append(AZSBlockListItem(blockID: base64EncodedId, blockListMode: .uncommitted))
func uploadBlockList() {
blobBlock?.uploadBlockList(from: blockList, completionHandler: { (bError) in
guard bError == nil else {
print(bError!)
uploadBlockList()
return
}
})
}
func uploadBlock() {
blobBlock?.uploadBlock(from: chunk, blockID: base64EncodedId, completionHandler: { (error) in
guard error == nil else {
uploadBlock()
return
}
guard offset >= length else {
nextChunk()
return
}
uploadBlockList()
})
}
uploadBlock()
}
}
nextChunk()
}
This is an image displaying the high memory usage issue.
Upvotes: 2
Views: 265
Reputation: 726
Try this code as mentioned by @Cy-4AH
@IBAction func onReadStream(_ sender: UIButton) {
guard videoURL != nil else { return }
guard let inputStream = InputStream(url: videoURL!) else { return }
do {
try readingInputStream(reading: inputStream)
} catch {
print(error)
}
}
func readingInputStream(reading input: InputStream) throws {
input.open()
defer {
input.close()
}
let bufferSize = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer {
buffer.deallocate()
}
while input.hasBytesAvailable {
let read = input.read(buffer, maxLength: bufferSize)
if read < 0 {
throw input.streamError!
} else if read == 0 {
break
}
let data = Data(bytes: buffer, count: read)
print(data)
// Here you can upload data to server
}
}
Upvotes: 1