它工作得很好,但神秘的是,上传停止了工作。我没有更改Cognito或IAM设置。
我可以下载,但我无法上传。我收到以下错误消息:
会话任务失败,错误:错误Domain = NSPOSIXErrorDomain 代码= 54“由同行重置连接”
UserInfo = {_ kCFStreamErrorCodeKey = 54,_kCFStreamErrorDomainKey = 1} 2016-12-10 19:06:44.484704 aws-s3-pods [42605:831200] []
nw_endpoint_handler_add_write_request [3.1 54.231.98.131:443失败 socket-flow(满意)]不能接受写请求2016-12-10 19:06:44.485410 aws-s3-pods [42605:831243] [] __tcp_connection_write_eof_block_invoke写入关闭回调收到错误:[22]无效参数
upload
方法中的错误发生在行transferManager.upload(uploadRequest).continue
中(完整代码如下)。
与亚马逊互动的类
//
// AmazonS3.swift
// challenge3
//
// Created by Bruno Macabeus Aquino on 07/12/16.
// Copyright © 2016 Bruno Macabeus Aquino. All rights reserved.
//
import Foundation
import AWSCore
import AWSS3
let REGION_TYPE = AWSRegionType.usEast1
let IDENTITY_POOL_ID = "XXXXXXXXXXXXXXXX"
enum AmazonS3DownloadErros {
case noSuchBucket
case noSuchKey
case others
}
enum AmazonS3UploadErros {
case noSuchBucket
case others
}
class AmazonS3 {
static let sharedInstance = AmazonS3()
let deviceDirectoryForUploads: URL
init() {
// credenciais
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: REGION_TYPE,
identityPoolId: IDENTITY_POOL_ID)
let configuration = AWSServiceConfiguration(
region: .usEast1,
credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
// create temp directory to make upload
func createLocalTmpDirectory(_ directoryName: String) -> URL? {
do {
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(directoryName)
try
FileManager.default.createDirectory(
at: url,
withIntermediateDirectories: true,
attributes: nil)
return url
} catch let error as NSError {
print("Creating \(directoryName) directory failed. Error: \(error)")
return nil
}
}
self.deviceDirectoryForUploads = createLocalTmpDirectory("upload")!
}
func download(bucket: String, key: String, errorHandle: @escaping (_ enumError: AmazonS3DownloadErros, _ taskResult: AWSTask<AnyObject>, _ error: Error) -> Void, completion: @escaping (_ resultObjectOutput: AWSS3TransferManagerDownloadOutput, _ filePath: String) -> Void) {
let downloadRequest = AWSS3TransferManagerDownloadRequest()!
downloadRequest.bucket = bucket
downloadRequest.key = key
let transferManager = AWSS3TransferManager.default()!
transferManager.download(downloadRequest).continue({
task in
if let error = task.error {
let errorCode = (error._userInfo as! [String: String])["Code"]
if errorCode == "NoSuchKey" {
errorHandle(.noSuchKey, task, error)
} else if errorCode == "NoSuchBucket" {
errorHandle(.noSuchBucket, task, error)
} else {
errorHandle(.others, task, error)
}
} else {
let results = task.result! as! AWSS3TransferManagerDownloadOutput
let body = results.body as! NSURL
completion(results, body.path!)
}
return nil
})
}
func imageToUrl(image: UIImage, fileName: String) -> URL {
let fileURL = deviceDirectoryForUploads.appendingPathComponent(fileName)
try! UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
return fileURL
}
func upload(bucket: String, key: String, filePath: URL, errorHandle: @escaping (_ enumError: AmazonS3UploadErros, _ taskResult: AWSTask<AnyObject>, _ error: Error) -> Void,
completion: @escaping (_ resultObjectOutput: AWSS3TransferManagerUploadOutput) -> Void) {
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = filePath
uploadRequest.key = key
uploadRequest.bucket = bucket
let transferManager = AWSS3TransferManager.default()!
transferManager.upload(uploadRequest).continue({
task in
if let error = task.error {
let errorCode = (error._userInfo as! [String: String])["Code"]
if errorCode == "NoSuchBucket" {
errorHandle(.noSuchBucket, task, error)
} else {
errorHandle(.others, task, error)
}
} else {
let results = task.result! as! AWSS3TransferManagerUploadOutput
completion(results)
}
return nil
})
}
func uploadImage(bucket: String, key: String, image: UIImage, errorHandle: @escaping (_ enumError: AmazonS3UploadErros, _ taskResult: AWSTask<AnyObject>, _ error: Error) -> Void,
completion: @escaping (_ resultObjectOutput: AWSS3TransferManagerUploadOutput) -> Void) {
self.upload(
bucket: bucket,
key: key,
filePath: imageToUrl(image: image, fileName: key.components(separatedBy: "/").last!),
errorHandle: errorHandle,
completion: completion
)
}
}
在控制器中使用upload
:
AmazonS3.sharedInstance.uploadImage(
bucket: "eventbeeapp",
key: "luffy.jpg",
image: #imageLiteral(resourceName: "luffy"),
errorHandle: {
_, _, _ in
print("--- ERROR ---")
}, completion: {
_ in
print("--- OK ---")
})