In the example I will be downloading an image from my S3 bucket using S3TransferUtility for iOS in swift. You can find the source here on github
In the example i have 2 outlets:
1 2 | @IBOutlet weak var progressView : UIProgressView ! @IBOutlet weak var imageView : UIImageView ! |
This function defines what s3 bucket we are using and the file/image we need to download. It then handles the progress view and finally the image view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | func downloadImage (){ var completionHandler : AWSS3TransferUtilityDownloadCompletionHandlerBlock ? //downloading image let S3BucketName : String = "yourBucketName" let S3DownloadKeyName : String = "example-image-1.png" 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 ) self . progressView . progress = progress // self.statusLabel.text = "Downloading..." NSLog ( "Progress is: %f" , progress ) }) } self . completionHandler = { ( task , location , data , error ) - > Void in dispatch_async ( dispatch_get_main_queue (), { if (( error ) != nil ){ NSLog ( "Failed with error" ) NSLog ( "Error: %@" , error !); // self.statusLabel.text = "Failed" } else if ( self . progressView . progress != 1.0 ) { // self.statusLabel.text = "Failed" NSLog ( "Error: Failed - Likely due to invalid region / filename" ) } else { // self.statusLabel.text = "Success" self . imageView . image = 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 { NSLog ( "Error: %@" , error . localizedDescription ); // self.statusLabel.text = "Failed" } if let exception = task . exception { NSLog ( "Exception: %@" , exception . description ); // self.statusLabel.text = "Failed" } if let _ = task . result { // self.statusLabel.text = "Starting Download" NSLog ( "Download Starting!" ) // Do something with uploadTask. } return nil ; } } |
Hi jzorz,
I am getting this error pls help me, Nil is not compatible with expected argument type ‘NSURL’ near the line below
-> transferUtility?.downloadToURL(nil, bucket: ……
Hi Puneeth. Do you have var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock? in your controller? I’ve added source files on github so you can quickly view how I did it. Github