Skip to content

Instantly share code, notes, and snippets.

@gtongy
Last active May 12, 2019 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtongy/842c25548a6c264f107aa762a7807830 to your computer and use it in GitHub Desktop.
Save gtongy/842c25548a6c264f107aa762a7807830 to your computer and use it in GitHub Desktop.
RxSwift S3 Upload Sample
AWS_IDENTITY_POOL_ID="xxxxxxx"
import UIKit
import CoreData
import AWSCognito
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.initEnv()
let env = ProcessInfo.processInfo.environment
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType:.APNortheast1,
identityPoolId: env["AWS_IDENTITY_POOL_ID"]!
)
let configuration = AWSServiceConfiguration(region:.APNortheast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
RxImagePickerDelegateProxy.register { RxImagePickerDelegateProxy(imagePicker: $0) }
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "appname")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
private func initEnv() {
guard let path = Bundle.main.path(forResource: ".env", ofType: nil) else {
fatalError("Not found: '/path/to/.env'.\nPlease create .env file reference from .env.sample")
}
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let str = String(data: data, encoding: .utf8) ?? "Empty File"
let clean = str.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "'", with: "")
let envVars = clean.components(separatedBy:"\n")
for envVar in envVars {
let keyVal = envVar.components(separatedBy:"=")
if keyVal.count == 2 {
setenv(keyVal[0], keyVal[1], 1)
}
}
} catch {
fatalError(error.localizedDescription)
}
}
}
import UIKit
@IBDesignable
public final class PreviewImage: UIImageView {
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configure()
}
private func configure() {
backgroundColor = #colorLiteral(red: 0, green: 0.6730770469, blue: 1, alpha: 1)
layer.shadowOpacity = 0.3
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowRadius = 4
layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
}
}
import UIKit
@IBDesignable
public final class PrimaryActionButton: UIButton {
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configure()
}
private func configure() {
backgroundColor = #colorLiteral(red: 0, green: 0.6730770469, blue: 1, alpha: 1)
layer.cornerRadius = 24
titleLabel?.font = UIFont.boldSystemFont(ofSize: 19)
setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
layer.shadowOpacity = 0.3
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowRadius = 4
layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
}
}
import RxSwift
import RxCocoa
import UIKit
open class RxImagePickerDelegateProxy
: RxNavigationControllerDelegateProxy, UIImagePickerControllerDelegate {
public init(imagePicker: UIImagePickerController) {
super.init(navigationController: imagePicker)
}
}
import RxSwift
import RxCocoa
import UIKit
import Foundation
struct SelectPhotoViewModelInput {
let targetController: ViewController
let selectPhotoButton: Observable<Void>
let previewImage: UIImageView
}
protocol SelectPhotoViewModelOutout {}
protocol SelectPhotoViewModelType {
var outputs: SelectPhotoViewModelOutout? { get }
func setup(input: SelectPhotoViewModelInput)
}
class SelectPhotoViewModel: SelectPhotoViewModelType {
var outputs: SelectPhotoViewModelOutout?
private let disposeBag = DisposeBag()
init() {
self.outputs = self
}
func setup(input: SelectPhotoViewModelInput) {
input.selectPhotoButton
.subscribe({ [unowned self] _ in
UIImagePickerController.rx.createWithParent(input.targetController) { picker in
picker.sourceType = .photoLibrary
picker.allowsEditing = false
}
.flatMap {
$0.rx.didFinishPickingMediaWithInfo
}
.take(1)
.map { info in
return info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
.bind(to: input.previewImage.rx.image)
.disposed(by: self.disposeBag)
})
.disposed(by: self.disposeBag)
}
}
extension SelectPhotoViewModel: SelectPhotoViewModelOutout {}
import RxSwift
import RxCocoa
import UIKit
extension Reactive where Base: UIImagePickerController {
public var didFinishPickingMediaWithInfo: Observable<[UIImagePickerController.InfoKey: Any]> {
return delegate
.methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerController(_:didFinishPickingMediaWithInfo:)))
.map({ (a) in
return try castOrThrow(Dictionary<UIImagePickerController.InfoKey, Any>.self, a[1])
})
}
public var didCancel: Observable<()> {
return delegate
.methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerControllerDidCancel(_:)))
.map { _ in () }
}
public var task: Observable<[UIImagePickerController.InfoKey: Any]> {
return Observable
.of(
didFinishPickingMediaWithInfo.map { Optional.some($0)! },
didCancel.map { Optional.none! }
)
.merge()
.take(1)
}
}
fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
import UIKit
import RxSwift
import RxCocoa
func dismissViewController(_ viewController: UIViewController, animated: Bool) {
if viewController.isBeingDismissed || viewController.isBeingPresented {
DispatchQueue.main.async {
dismissViewController(viewController, animated: animated)
}
return
}
if viewController.presentingViewController != nil {
viewController.dismiss(animated: animated, completion: nil)
}
}
extension Reactive where Base: UIImagePickerController {
static func createWithParent(_ parent: UIViewController?, animated: Bool = true, configureImagePicker: @escaping (UIImagePickerController) throws -> Void = { x in }) -> Observable<UIImagePickerController> {
return Observable.create { [weak parent] observer in
let imagePicker = UIImagePickerController()
let dismissDisposable = imagePicker.rx
.didCancel
.subscribe(onNext: { [weak imagePicker] _ in
guard let imagePicker = imagePicker else {
return
}
dismissViewController(imagePicker, animated: animated)
})
do {
try configureImagePicker(imagePicker)
}
catch let error {
observer.on(.error(error))
return Disposables.create()
}
guard let parent = parent else {
observer.on(.completed)
return Disposables.create()
}
parent.present(imagePicker, animated: animated, completion: nil)
observer.on(.next(imagePicker))
return Disposables.create(dismissDisposable, Disposables.create {
dismissViewController(imagePicker, animated: animated)
})
}
}
}
import RxSwift
import RxCocoa
import UIKit
import AWSS3
import Foundation
struct UploadPhotoViewModelInput {
let targetController: ViewController
let uploadPhotoButton: Observable<Void>
let previewImage: UIImageView
}
protocol UploadPhotoViewModelOutout {}
protocol UploadPhotoViewModelType {
var outputs: UploadPhotoViewModelOutout? { get }
func setup(input: UploadPhotoViewModelInput)
}
class UploadPhotoViewModel: UploadPhotoViewModelType {
var outputs: UploadPhotoViewModelOutout?
private let disposeBag = DisposeBag()
init() {
self.outputs = self
}
func setup(input: UploadPhotoViewModelInput) {
input.uploadPhotoButton
.subscribe({ [unowned self] _ in
let tmpPath:String = NSTemporaryDirectory() + "image.png"
let localFilePath:URL = self.savePNGImage(to: tmpPath, image: input.previewImage.image!) as URL
let transfer: AWSS3TransferUtility = AWSS3TransferUtility.default()
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, progress) in
DispatchQueue.main.async {
print("uploading...")
}
}
let completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async {
if error != nil {
print("error")
} else {
print("success")
}
}
}
transfer.uploadFile(localFilePath, bucket: "save-bucket-name", key: "key/image.png", contentType: "image/png", expression: expression, completionHandler: completionHandler)
})
.disposed(by: self.disposeBag)
}
private func savePNGImage(to filePath: String, image: UIImage) -> NSURL {
let imageData:NSData = image.pngData()! as NSData
imageData.write(toFile: filePath, atomically: true)
return NSURL(fileURLWithPath: filePath)
}
}
extension UploadPhotoViewModel: UploadPhotoViewModelOutout {}
import RxSwift
import RxCocoa
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var selectPhotoButton: PrimaryActionButton!
@IBOutlet weak var uploadPhotoButton: PrimaryActionButton!
@IBOutlet weak var previewImageView: UIImageView!
private let disposeBag = DisposeBag()
private var selectPhotoViewModel: SelectPhotoViewModel!
private var uploadPhotoViewModel: UploadPhotoViewModel!
override func viewDidLoad() {
super.viewDidLoad()
setupViewModel()
}
private func setupViewModel() {
selectPhotoViewModel = SelectPhotoViewModel()
selectPhotoViewModel.setup(input: SelectPhotoViewModelInput(
targetController: self,
selectPhotoButton: selectPhotoButton.rx.tap.asObservable(),
previewImage: previewImageView
))
uploadPhotoViewModel = UploadPhotoViewModel()
uploadPhotoViewModel.setup(input: UploadPhotoViewModelInput(
targetController: self,
uploadPhotoButton: uploadPhotoButton.rx.tap.asObservable(),
previewImage: previewImageView
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment