Swift - AWS S3 从照片库上传图像并下载 [英] Swift - AWS S3 Upload Image from Photo Library and download it

查看:44
本文介绍了Swift - AWS S3 从照片库上传图像并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了许多亚马逊文档,但没有找到足够的信息来使用 Swift 将图像上传和下载到 S3.
我该怎么做?

I've looked many amazon docs but didn't find enough information to upload and download images to S3 using Swift.
How can I do that?

推荐答案

在做了很多研究之后,我得到了这个工作,

After doing many research I've got this working,

import AWSS3
import AWSCore

上传:

我假设你已经实现了 UIImagePickerControllerDelegate.

I assume you have implemented UIImagePickerControllerDelegate already.

第 1 步:

  • 创建用于保存 url 的变量:

  • Create variable for holding url:

var imageURL = NSURL()

  • 创建上传完成处理程序 obj:

  • Create upload completion handler obj:

    var uploadCompletionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
    

  • 第 2 步:imagePickerController(_:didFinishPickingMediaWithInfo:) 获取图片 URL:

    Step 2: Get Image URL from imagePickerController(_:didFinishPickingMediaWithInfo:):

    • 在此委托方法中设置 imageURL 的值:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
    
        //getting details of image
        let uploadFileURL = info[UIImagePickerControllerReferenceURL] as! NSURL
    
        let imageName = uploadFileURL.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
    
        // getting local path
        let localPath = (documentDirectory as NSString).stringByAppendingPathComponent(imageName!)
    
    
        //getting actual image
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let data = UIImagePNGRepresentation(image)
        data!.writeToFile(localPath, atomically: true)
    
        let imageData = NSData(contentsOfFile: localPath)!
        imageURL = NSURL(fileURLWithPath: localPath)
    
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    

    第 3 步:imageURL 设置为将图像上传到您的存储桶后调用此 uploadImage 方法:

    Step 3: Call this uploadImage method after imageURL set to Upload Image to your bucket:

    func uploadImage(){
    
        //defining bucket and upload file name
        let S3BucketName: String = "bucketName"
        let S3UploadKeyName: String = "public/testImage.jpg"
    
    
        let expression = AWSS3TransferUtilityUploadExpression()
        expression.uploadProgress = {(task: AWSS3TransferUtilityTask, bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) in
            dispatch_async(dispatch_get_main_queue(), {
                let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
                print("Progress is: (progress)")
            })
        }
    
        self.uploadCompletionHandler = { (task, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), {
                if ((error) != nil){
                    print("Failed with error")
                    print("Error: (error!)");
                }
                else{
                    print("Sucess")
                }
            })
        }
    
        let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
    
        transferUtility.uploadFile(imageURL, bucket: S3BucketName, key: S3UploadKeyName, contentType: "image/jpeg", expression: expression, completionHander: uploadCompletionHandler).continueWithBlock { (task) -> AnyObject! in
            if let error = task.error {
                print("Error: (error.localizedDescription)")
            }
            if let exception = task.exception {
                print("Exception: (exception.description)")
            }
            if let _ = task.result {
                print("Upload Starting!")
            }
    
            return nil;
        }
    }
    

    下载:

    func downloadImage(){
    
        var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
    
        let S3BucketName: String = "bucketName"
        let S3DownloadKeyName: String = "public/testImage.jpg"
    
        let expression = AWSS3TransferUtilityDownloadExpression()
        expression.downloadProgress = {(task: AWSS3TransferUtilityTask, bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) in
            dispatch_async(dispatch_get_main_queue(), {
                let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
                print("Progress is: (progress)")
            })
        }
    
        completionHandler = { (task, location, data, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), {
                if ((error) != nil){
                    print("Failed with error")
                    print("Error: (error!)")
                }
                else{
                    //Set your image
                    var downloadedImage = UIImage(data: data!)
                }
            })
        }
    
        let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
    
        transferUtility.downloadToURL(nil, bucket: S3BucketName, key: S3DownloadKeyName, expression: expression, completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in
            if let error = task.error {
                print("Error: (error.localizedDescription)")
            }
            if let exception = task.exception {
                print("Exception: (exception.description)")
            }
            if let _ = task.result {
                print("Download Starting!")
            }
            return nil;
        }
    
    }
    

    参考.用于上传图片

    参考.用于下载图像

    非常感谢 jzorz

    这篇关于Swift - AWS S3 从照片库上传图像并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆