Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

ios - Swift - AWS S3 Upload Image from Photo Library and download it

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After doing many research I've got this working,

import AWSS3
import AWSCore

Upload:

I assume you have implemented UIImagePickerControllerDelegate already.

Step 1:

  • Create variable for holding url:

    var imageURL = NSURL()
    
  • Create upload completion handler obj:

    var uploadCompletionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
    

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

  • Set value of imageURL in this delegate method:

    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)
    }
    

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;
    }
}

Download:

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;
    }

}

Ref. for upload image

Ref. for download image

Many thanks to jzorz


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...