我使用swift 2.3和Alamofire与multipartFormData异步上传文件,似乎无法确定在我的连接超时或丢失连接后是否可以创建简历并在手机上重新建立。
我想要的是在失败时恢复上传,例如:我上传一个大文件。它上传了55%,然后我失去了我的互联网连接。当我重新获得互联网连接时,我希望上传从55%继续而不是从0%再次开始。
以下是我用于上传文件的代码:
class FileUploadHelper
{
class func Upload(numberOfTimes: Int, index: Int, command: String, nsData: NSData, fileName: String, mimeType: String, progress: (index: Int, progressPercentage: Int) -> Void, error: (index: Int, fileUploadError : FileUploadError) -> Void, completed: (index: Int, dataFail: Int) -> Void, badConnection: () -> Void)
{
Alamofire.upload(.POST, ResourceHelper.ServiceBaseUrl + command, multipartFormData:
{
multipartFormData in
multipartFormData.appendBodyPart(data: nsData, name: "test", fileName: fileName, mimeType: mimeType)
}, encodingCompletion:
{
encodingResult in
encodingCompleted(numberOfTimes, index: index, command: command, nsData: nsData, fileName: fileName, mimeType: mimeType, encodingResult: encodingResult, progress: progress, error: error, completed: completed, badConnection: badConnection)
}
)
}
class func encodingCompleted( numberOfTimes: Int, index: Int, command: String, nsData: NSData, fileName: String, mimeType: String , encodingResult: Manager.MultipartFormDataEncodingResult, progress: (index: Int, progressPercentage: Int) -> Void, error: (index: Int, fileUploadError : FileUploadError) -> Void, completed: (index: Int, dataFail: Int) -> Void, badConnection: () -> Void)
{
switch encodingResult {
case .Success (let upload, _, _):
upload.responseString {
response in
var out: NSInteger = 0
response.data!.getBytes(&out, length: sizeof(NSInteger))
switch response.result {
case .Success:
dispatch_async(dispatch_get_main_queue(), {
completed(index: index, dataFail: out)
})
case .Failure:
if (numberOfTimes > 0) {
AWBanner.showWithDuration(7, delay: 0, message: NSLocalizedString("Bad Connection - Attempting to upload", comment: ""), backgroundColor: UIColor.redColor(), textColor: UIColor.whiteColor(), originY: 40.0)
FileUploadHelper.Upload(numberOfTimes - 1, index: index, command: command, nsData: nsData, fileName: fileName,mimeType: mimeType, progress: progress, error: error, completed: completed, badConnection: badConnection)
}
else {
badConnection()
}
}
}
upload.progress
{
bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
dispatch_async(dispatch_get_main_queue(), {
progress(index: index, progressPercentage: Int(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) * 100))
})
}
case .Failure(let encodingError):
dispatch_async(dispatch_get_main_queue(), {
error(index: index, fileUploadError: FileUploadError.Failed(encodingError: encodingError))
})
}
}
}