我必须将映像上传到Amazon AWS S3存储,但是始终向我显示错误,(网络连接丢失。)

时间:2018-12-17 12:26:52

标签: swift amazon-web-services amazon-s3

我无法使用访问密钥和秘密密钥将图像上传到亚马逊s3存储,如果有人使用访问密钥和秘密密钥进行了此类示例,请分享,我也编写了此代码,请检阅如果我犯了任何错误,请确定。 这是代码:

import UIKit
import AWSS3
import AWSCore

class ViewController: UIViewController {

let accessKey = "myaccesskey here"
let secretKey = "mysecretkey here"

let S3BucketName = "bucketname"
let remoteName = "test.jpg"

@IBOutlet var activtyIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
    super.viewDidLoad()

    let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
    let configuration = AWSServiceConfiguration(region:AWSRegionType.USEast1, credentialsProvider:credentialsProvider)

    AWSServiceManager.default().defaultServiceConfiguration = configuration

}

@IBAction func uploadAction(_ sender: UIBarButtonItem) {

    print("Tapped")
    activtyIndicator.startAnimating()
    let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(remoteName)
    let image = UIImage(named: "test")
    let data = image!.jpegData(compressionQuality: 0.9)
    do {
        try data?.write(to: fileURL)
    }
    catch {}

    let uploadRequest = AWSS3TransferManagerUploadRequest()!
    uploadRequest.body = fileURL
    uploadRequest.key = remoteName
    uploadRequest.bucket = S3BucketName
    uploadRequest.contentType = "image/jpeg"
    uploadRequest.acl = .publicRead

    let transferManager = AWSS3TransferManager.default()

    transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in
        DispatchQueue.main.async {
            self?.activtyIndicator.stopAnimating()
        }

        if let error = task.error {
            print("Upload failed with error: (\(error.localizedDescription))")
        }

        if task.result != nil {
            let url = AWSS3.default().configuration.endpoint.url
            let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
            if let absoluteString = publicURL?.absoluteString {
                print("Uploaded to:\(absoluteString)")
            }
        }

        return nil
    }
  }
}

错误如下:

“上传失败,出现错误:(网络连接丢失。)”

0 个答案:

没有答案