Skip to content

Instantly share code, notes, and snippets.

@imnaveensharma
Created July 25, 2020 04:55
Show Gist options
  • Save imnaveensharma/84e3317fea012d6581b172f7358ea45c to your computer and use it in GitHub Desktop.
Save imnaveensharma/84e3317fea012d6581b172f7358ea45c to your computer and use it in GitHub Desktop.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
AWSMediaUploadManager.shared.initializeS3()
return true
}
}
import UIKit
import AWSS3
//pod 'AWSS3'
//https://github.com/maximbilan/Swift-Amazon-S3-Uploading-Tutorial
//https://www.swiftdevcenter.com/upload-image-video-audio-and-any-type-of-files-to-aws-s3-bucket-swift/
typealias progressBlock = (_ progress: Double) -> Void
typealias completionBlock = (_ response: Any?, _ error: Error?) -> Void
class AWSMediaUploadManager {
// MARK: - Properties ::
internal static let shared: AWSMediaUploadManager = {
AWSMediaUploadManager()
}()
private let bucketName = ""
private let accessKey = ""
private let secretAccessKey = ""
private let poolId = ""
// MARK: Initialization ::
private init() {}
// MARK: Internal Functiopns ::
internal func initializeS3() {
//let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APSouth1, identityPoolId: self.poolId)
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: self.accessKey, secretKey: self.secretAccessKey)
let configuration = AWSServiceConfiguration(region: .APSouth1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
}
// Upload image using UIImage object
internal func uploadImage(image: UIImage, progress: progressBlock?, completion: completionBlock?) {
guard let imageData = image.jpegData(compressionQuality: 1.0) else {
let error = NSError(domain:"", code:402, userInfo:[NSLocalizedDescriptionKey: "Invalid Image"])
completion?(nil, error)
return
}
let tmpPath = NSTemporaryDirectory() as String
let fileName: String = ProcessInfo.processInfo.globallyUniqueString + (".jpeg")
let filePath = tmpPath + "/" + fileName
let fileUrl = URL(fileURLWithPath: filePath)
print("AWSMediaUploadManager :: Image File Name :: \(fileName)")
print("AWSMediaUploadManager :: Image File URL :: \(fileUrl)")
do {
try imageData.write(to: fileUrl)
self.uploadFile(fileUrl: fileUrl, fileName: fileName, contenType: "image", progress: progress, completion: completion)
} catch {
let error = NSError(domain:"", code:402, userInfo:[NSLocalizedDescriptionKey: "Invalid Image"])
completion?(nil, error)
}
}
// Upload video from local path url
func uploadVideo(videoUrl: URL, progress: progressBlock?, completion: completionBlock?) {
let fileName = self.getUniqueFileName(fileUrl: videoUrl)
print("AWSMediaUploadManager :: Video File Name :: \(fileName)")
self.uploadFile(fileUrl: videoUrl, fileName: fileName, contenType: "video", progress: progress, completion: completion)
}
// Upload auido from local path url
func uploadAudio(audioUrl: URL, progress: progressBlock?, completion: completionBlock?) {
let fileName = self.getUniqueFileName(fileUrl: audioUrl)
print("AWSMediaUploadManager :: Audio File Name :: \(fileName)")
self.uploadFile(fileUrl: audioUrl, fileName: fileName, contenType: "audio", progress: progress, completion: completion)
}
// Upload files like Text, Zip, etc from local path url
func uploadOtherFile(fileUrl: URL, conentType: String, progress: progressBlock?, completion: completionBlock?) {
let fileName = self.getUniqueFileName(fileUrl: fileUrl)
print("AWSMediaUploadManager :: Other File Name :: \(fileName)")
self.uploadFile(fileUrl: fileUrl, fileName: fileName, contenType: conentType, progress: progress, completion: completion)
}
// Get unique file name
func getUniqueFileName(fileUrl: URL) -> String {
let strExt: String = "." + (URL(fileURLWithPath: fileUrl.absoluteString).pathExtension)
return (ProcessInfo.processInfo.globallyUniqueString + (strExt))
}
//MARK:- AWS file upload
// fileUrl : file local path url
// fileName : name of file, like "myimage.jpeg" "video.mov"
// contenType: file MIME type
// progress: file upload progress, value from 0 to 1, 1 for 100% complete
// completion: completion block when uplaoding is finish, you will get S3 url of upload file here
private func uploadFile(fileUrl: URL, fileName: String, contenType: String, progress: progressBlock?, completion: completionBlock?) {
// Upload progress block
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, awsProgress) in
guard let uploadProgress = progress else { return }
DispatchQueue.main.async {
uploadProgress(awsProgress.fractionCompleted)
}
}
// Completion block
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
if error == nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(self.bucketName).appendingPathComponent(fileName)
print("AWSMediaUploadManager :: File URL :: \(fileUrl)")
print("AWSMediaUploadManager :: File Name :: \(fileName)")
print("AWSMediaUploadManager :: URL :: \(String(describing: url))")
print("AWSMediaUploadManager :: Public URL :: \(String(describing: publicURL))")
if let completionBlock = completion {
//let dict = ["url": publicURL?.absoluteString, ""]
//completionBlock(publicURL?.absoluteString, nil)
completionBlock(fileName, nil)
}
} else {
if let completionBlock = completion {
completionBlock(nil, error)
}
}
})
}
// Start uploading using AWSS3TransferUtility
let awsTransferUtility = AWSS3TransferUtility.default()
awsTransferUtility.uploadFile(fileUrl, bucket: bucketName, key: fileName, contentType: contenType, expression: expression, completionHandler: completionHandler).continueWith { (task) -> Any? in
if let error = task.error {
print("AWSMediaUploadManager :: Error is :: \(error.localizedDescription)")
}
if let _ = task.result {
// your uploadTask
}
return nil
}
}
// MARK: Private Functions ::
private func getRandomMediaName(fileExtension: String = "JPG") -> String
{
let timestamp = String(Int(NSDate().timeIntervalSince1970))
//let randomString = String.random()
return timestamp + ".\(fileExtension)"
//return UUID().uuidString + ".\(fileExtension)"
}
}
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var lblFileName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func uploadImage(_ sender: Any) {
guard let image = UIImage(named: "your-image") else { return }
AWSMediaUploadManager.shared.uploadImage(image: image, progress: {[weak self] ( uploadProgress) in
guard let strongSelf = self else { return }
print("Upload Progress :: \(Float(uploadProgress))")
strongSelf.progressView.progress = Float(uploadProgress)
}) {[weak self] (uploadedFileName, error) in
guard let strongSelf = self else { return }
if let fileName = uploadedFileName as? String {
print("Uploaded file name :: \(fileName)")
strongSelf.lblFileName.text = fileName
} else {
print("\(String(describing: error?.localizedDescription))")
}
}
}
@IBAction func uploadVideo(_ sender: Any) {
//guard let path = Bundle.main.path(forResource: "Video", ofType: "mov") else { return }
let videoUrl = URL(fileURLWithPath: "your video file path")
AWSMediaUploadManager.shared.uploadVideo(videoUrl: videoUrl, progress: { [weak self] (uploadProgress) in
guard let strongSelf = self else { return }
print("Upload Progress :: \(Float(uploadProgress))")
strongSelf.progressView.progress = Float(uploadProgress)
}) { [weak self] (uploadedFileName, error) in
guard let strongSelf = self else { return }
if let fileName = uploadedFileName as? String {
print("Uploaded file name :: \(fileName)")
strongSelf.lblFileName.text = fileName
} else {
print("Error :: \(String(describing: error?.localizedDescription))")
}
}
}
@IBAction func uploadAudio(_ sender: Any) {
let audioUrl = URL(fileURLWithPath: "your audio local file path")
AWSMediaUploadManager.shared.uploadAudio(audioUrl: audioUrl, progress: { [weak self] (uploadProgress) in
guard let strongSelf = self else { return }
print("Upload Progress :: \(Float(uploadProgress))")
strongSelf.progressView.progress = Float(uploadProgress)
}) { [weak self] (uploadedFileName, error) in
guard let strongSelf = self else { return }
if let fileName = uploadedFileName as? String {
print("Uploaded file name :: \(fileName)")
strongSelf.lblFileName.text = fileName
} else {
print("Error :: \(String(describing: error?.localizedDescription))")
}
}
}
//Upload other files like plain text, zip, etc
@IBAction func uploadFile(_ sender: Any) {
let fileURL = URL(fileURLWithPath: "your other file path")
AWSMediaUploadManager.shared.uploadOtherFile(fileUrl: fileURL, conentType:"txt", progress: { [weak self] (uploadProgress) in
guard let strongSelf = self else { return }
print("Upload Progress :: \(Float(uploadProgress))")
strongSelf.progressView.progress = Float(uploadProgress)
}) { [weak self] (uploadedFileName, error) in
guard let strongSelf = self else { return }
if let fileName = uploadedFileName as? String {
print("Uploaded file name :: \(fileName)")
strongSelf.lblFileName.text = fileName
} else {
print("Error :: \(String(describing: error?.localizedDescription))")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment