This repository was archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathFileUploadOperation.swift
51 lines (44 loc) · 1.6 KB
/
FileUploadOperation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// FileUploadOperation.swift
// Rebekka
//
// Created by Constantine Fry on 25/05/15.
// Copyright (c) 2015 Constantine Fry. All rights reserved.
//
import Foundation
/** Operation for file uploading. */
internal class FileUploadOperation: WriteStreamOperation {
fileprivate var fileHandle: FileHandle?
var fileURL: URL!
override func start() {
do {
self.fileHandle = try FileHandle(forReadingFrom: fileURL)
self.startOperationWithStream(self.writeStream)
} catch let error as NSError {
self.error = error
self.fileHandle = nil
self.finishOperation()
}
}
override func streamEventEnd(_ aStream: Stream) -> (Bool, NSError?) {
self.fileHandle?.closeFile()
return (true, nil)
}
override func streamEventError(_ aStream: Stream) {
super.streamEventError(aStream)
self.fileHandle?.closeFile()
}
override func streamEventHasSpace(_ aStream: Stream) -> (Bool, NSError?) {
if let writeStream = aStream as? OutputStream {
let offsetInFile = self.fileHandle!.offsetInFile
let data = self.fileHandle!.readData(ofLength: 1024)
let writtenBytes = writeStream.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
if writtenBytes > 0 {
self.fileHandle?.seek(toFileOffset: offsetInFile + UInt64(writtenBytes))
} else if writtenBytes == -1 {
self.finishOperation()
}
}
return (true, nil)
}
}