This uses the SwiftyDropbox library to upload a file from a NSData
to the Dropbox account, using upload sessions for larger files, handling every error case:
import UIKit
import SwiftyDropbox
class ViewController: UIViewController {
// replace this made up data with the real data
let data = String(count: 20 * 1024 * 1024, repeatedValue: Character("A")).dataUsingEncoding(NSUTF8StringEncoding)!
let chunkSize = 5 * 1024 * 1024 // 5 MB
var offset = 0
var sessionId = ""
// replace this with your desired destination path:
let destPath = "/SwiftyDropbox_upload.txt"
override func viewDidLoad() {
super.viewDidLoad()
Dropbox.authorizedClient = DropboxClient(...)
doUpload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func doUpload() {
let fileSize = data.length
print("Have \(fileSize) bytes to upload.")
if (fileSize < chunkSize) {
print("Using non-chunked uploading...")
Dropbox.authorizedClient!.files.upload(path:destPath, input:data).response { response, error in
if let metadata = response {
print(metadata)
} else if let callError = error {
print("upload failed")
switch callError as CallError {
case .RouteError(let boxed, let requestId):
print("RouteError[\(requestId)]:")
switch boxed.unboxed as Files.UploadError {
case .Path(let uploadError):
print("Path:")
switch uploadError.reason as Files.WriteError {
case .MalformedPath(let malformedPathError):
print("MalformedPath: \(malformedPathError)")
case .Conflict(let writeConflictError):
print("Conflict:")
switch writeConflictError {
case .File:
print("File")
case .FileAncestor:
print("FileAncestor")
case .Folder:
print("Folder")
case .Other:
print("Other")
}
case .DisallowedName:
print("DisallowedName")
case .InsufficientSpace:
print("InsufficientSpace")
case .NoWritePermission:
print("NoWritePermission")
case .Other:
print("Other")
}
case .Other:
print("Other")
}
case .BadInputError(let message, let requestId):
print("BadInputError[\(requestId)]: \(message)")
case .HTTPError(let code, let message, let requestId):
print("HTTPError[\(requestId)]: \(code): \(message)")
case .InternalServerError(let code, let message, let requestId):
print("InternalServerError[\(requestId)]: \(code): \(message)")
case .OSError(let err):
print("OSError: \(err)")
case .RateLimitError:
print("RateLimitError")
}
}
}
} else {
print("Using chunked uploading...")
uploadFirstChunk()
}
}
func uploadFirstChunk() {
let size = min(chunkSize, data.length)
Dropbox.authorizedClient!.files.uploadSessionStart(input:
data.subdataWithRange(NSMakeRange(0, size)))
.response { response, error in
if let result = response {
self.sessionId = result.sessionId
self.offset += size
print("So far \(self.offset) bytes have been uploaded.")
self.uploadNextChunk()
} else if let callError = error {
print("uploadSessionStart failed")
switch callError as CallError {
case .RouteError(let error, let requestId):
print("RouteError[\(requestId)]: \(error)")
case .BadInputError(let message, let requestId):
print("BadInputError[\(requestId)]: \(message)")
case .HTTPError(let code, let message, let requestId):
print("HTTPError[\(requestId)]: \(code): \(message)")
case .InternalServerError(let code, let message, let requestId):
print("InternalServerError[\(requestId)]: \(code): \(message)")
case .OSError(let err):
print("OSError: \(err)")
case .RateLimitError:
print("RateLimitError")
}
}
}
}
func uploadNextChunk() {
if data.length - offset <= chunkSize {
let size = data.length - offset
Dropbox.authorizedClient!.files.uploadSessionFinish(
cursor: Files.UploadSessionCursor(
sessionId: self.sessionId, offset: UInt64(offset)),
commit: Files.CommitInfo(path:destPath),
input: data.subdataWithRange(NSMakeRange(offset, size)))
.response { response, error in
if let callError = error {
print("uploadSessionFinish failed")
switch callError as CallError {
case .RouteError(let boxed, let requestId):
print("RouteError[\(requestId)]:")
switch boxed.unboxed as Files.UploadSessionFinishError {
case .Path(let writeError):
print("Path: ")
switch writeError {
case .MalformedPath(let malformedPathError):
print("MalformedPath: \(malformedPathError)")
case .Conflict(let writeConflictError):
print("Conflict:")
switch writeConflictError {
case .File:
print("File")
case .FileAncestor:
print("FileAncestor")
case .Folder:
print("Folder")
case .Other:
print("Other")
}
case .DisallowedName:
print("DisallowedName")
case .InsufficientSpace:
print("InsufficientSpace")
case .NoWritePermission:
print("NoWritePermission")
case .Other:
print("Other")
}
case .LookupFailed(let uploadSessionLookupError):
print("LookupFailed:")
switch uploadSessionLookupError {
case .Closed:
print("Closed")
case .IncorrectOffset(let uploadSessionOffsetError):
print("IncorrectOffset: \(uploadSessionOffsetError)")
case .NotFound:
print("NotFound")
case .NotClosed:
print("NotFound")
case .Other:
print("Other")
}
case .TooManySharedFolderTargets:
print("TooManySharedFolderTargets")
case .Other:
print("Other")
}
case .BadInputError(let message, let requestId):
print("BadInputError[\(requestId)]: \(message)")
case .HTTPError(let code, let message, let requestId):
print("HTTPError[\(requestId)]: \(code): \(message)")
case .InternalServerError(let code, let message, let requestId):
print("InternalServerError[\(requestId)]: \(code): \(message)")
case .OSError(let err):
print("OSError: \(err)")
case .RateLimitError:
print("RateLimitError")
}
} else if let result = response {
print("Done!")
print(result)
}
}
} else {
Dropbox.authorizedClient!.files.uploadSessionAppendV2(
cursor: Files.UploadSessionCursor(sessionId: self.sessionId, offset: UInt64(offset)),
input: data.subdataWithRange(NSMakeRange(offset, chunkSize)))
.response { response, error in
if error == nil {
self.offset += self.chunkSize
print("So far \(self.offset) bytes have been uploaded.")
self.uploadNextChunk()
} else if let callError = error {
print("uploadSessionAppend failed")
switch callError as CallError {
case .RouteError(let boxed, let requestId):
print("RouteError[\(requestId)]:")
switch boxed.unboxed as Files.UploadSessionLookupError {
case .Closed:
print("Closed")
case .IncorrectOffset(let uploadSessionOffsetError):
print("IncorrectOffset: \(uploadSessionOffsetError)")
case .NotFound:
print("NotFound")
case .NotClosed:
print("NotClosed")
case .Other:
print("Other")
}
case .BadInputError(let message, let requestId):
print("BadInputError[\(requestId)]: \(message)")
case .HTTPError(let code, let message, let requestId):
print("HTTPError[\(requestId)]: \(code): \(message)")
case .InternalServerError(let code, let message, let requestId):
print("InternalServerError[\(requestId)]: \(code): \(message)")
case .OSError(let err):
print("OSError: \(err)")
case .RateLimitError:
print("RateLimitError")
}
}
}
}
}
}