IDE:XCode6 /
Swift
我正在尝试从AWS S3下载文件,我已正确设置所有库,下载代码为(相关部分)..
let downloadFilePath = "/Users/user1/myfile.json" //locally save file here let downloadingFileURL = NSURL.fileURLWithPath(downloadFilePath) ... let downloadRequest = awss3transfermanagerDownloadRequest() downloadRequest.bucket = s3BucketName downloadRequest.key = "myfile.json" //fileName on s3 downloadRequest.downloadingFileURL = downloadingFileURL let transferManager = awss3transfermanager.defaultS3TransferManager() transferManager.download(downloadRequest).continueWithBlock { (task: BFTask!) -> AnyObject! in if task.error != nil { println("Error downloading") println(task.error.description) } else { println(downloadFilePath) var mytext = String(contentsOfFile: downloadFilePath,encoding: NSUTF8StringEncoding,error: nil) println(mytext) }
这很好 – 文件保存到/Users/user1/myfile.json.
但我不希望文件被保存,只是抓住内容 – 我怎么能这样做?
解决方法
这是我用来下载图像的Swift代码.它不会保存图像,它只会将它添加到我在viewDidLoad()中声明的数组中
func downloadImage(key: String){ var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock? //downloading image let S3BucketName: String = "your_s3_bucketName" let S3DownloadKeyName: String = key 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) }) } 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.collectionImages[S3DownloadKeyName] = UIImage(data: data!) //reload the collectionView data to include new picture self.colView.reloadData() } }) } 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. /* dispatch_async(dispatch_get_main_queue(),{ self.colView.reloadData() }) */ } return nil; } }