Skip to content

Instantly share code, notes, and snippets.

@shinjism
Last active May 2, 2018 03:59
Show Gist options
  • Select an option

  • Save shinjism/090c003fbb484a9f5d0c9a08cb3d1396 to your computer and use it in GitHub Desktop.

Select an option

Save shinjism/090c003fbb484a9f5d0c9a08cb3d1396 to your computer and use it in GitHub Desktop.
iOSデバイスからS3へzipアップロード
import UIKit
import AWSCognito
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Amazon Cognito 認証情報プロバイダーを初期化します
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APNortheast1,
identityPoolId: "IDプールのID")
let configuration = AWSServiceConfiguration(region: .APNortheast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
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:.
}
}
# Uncomment the next line to define a global platform for your project
platform :ios, '10.0'
target 'CognitoSample' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for CognitoSample
pod 'SSZipArchive'
pod 'AWSCognito'
pod 'AWSS3'
target 'CognitoSampleTests' do
inherit! :search_paths
# Pods for testing
end
target 'CognitoSampleUITests' do
inherit! :search_paths
# Pods for testing
end
end
import UIKit
import SSZipArchive
import AWSS3
class ViewController: UIViewController {
@IBOutlet weak var uploadButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTappedUploadButton(_ sender: UIButton) {
// Documentsディレクトリ絶対パス
let documentDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
// アーカイブファイル名
let archiveFile = "archive.zip"
// アーカイブファイル絶対パス
let archivePath = documentDir.appendingPathComponent(archiveFile)
// アーカイブファイルパスワード
let archivePassword = "hogehoge"
// 送信ボタンの処理
let defaultAction = UIAlertAction(title: "アップロード", style: .default, handler: {
[archiveData, uploadData, showAlert] (action: UIAlertAction!) -> Void in
sender.isEnabled = false
// アーカイブ処理
if archiveData(archivePath, archivePassword) {
// アップロード処理
uploadData(archivePath, archiveFile, {
sender.isEnabled = true
showAlert("アップロード", "S3へのアップロードが完了しました。")
}, { error in
if let e = error as NSError? {
print("localizedDescription:\n\(e.localizedDescription)")
print("userInfo:\n\(e.userInfo)")
}
sender.isEnabled = true
showAlert("アップロード", "S3へのアップロードが失敗しました。")
})
} else {
sender.isEnabled = true
showAlert("アーカイブ", "アーカイブが失敗しました。")
}
})
// キャンセルボタンの処理
let cancelAction = UIAlertAction(title: "キャンセル", style: .cancel)
// 送信確認
let confirmation = UIAlertController(title: "確認", message: "S3へアップロードしてもいいですか?", preferredStyle: .alert)
confirmation.addAction(defaultAction)
confirmation.addAction(cancelAction)
self.present(confirmation, animated: true, completion: nil)
}
// アラート表示
func showAlert(title: String, message: String) {
// OKボタンの処理
let defaultAction = UIAlertAction(title: "OK", style: .default)
// アラート表示
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(defaultAction)
self.present(alert, animated: true, completion: nil)
}
// Documentsディレクトリ内のresourceディレクトリをアーカイブ
func archiveData(archivePath: String, password: String) -> Bool {
// Documentsディレクトリ絶対パス
let documentDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
// 圧縮元ファルパス = resource
let resourcePath = documentDir.appendingPathComponent("resource")
// パスワード付きデータ圧縮
return SSZipArchive.createZipFile(atPath: archivePath, withContentsOfDirectory: resourcePath, withPassword: password)
}
// archive.zipをS3へアップロード
func uploadData(archivePath: String, archiveFile: String, complete: @escaping () -> Void, failure: @escaping (Error?) -> Void) {
// Documentsディレクトリの絶対パス
let transferUtility = AWSS3TransferUtility.default()
let url = URL(fileURLWithPath: archivePath)
let bucket = "バケット名"
let contentType = "application/zip"
// アップロード中の処理
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, progress) in
DispatchQueue.main.async {
// Do something e.g. Update a progress bar.
}
}
// アップロード後の処理
let completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async {
// Do something e.g. Alert a user for transfer completion.
// On failed uploads, `error` contains the error object.
if let error = error {
failure(error) // 失敗
} else {
complete() // 成功
}
}
}
// アップロード
transferUtility.uploadFile(
url,
bucket: bucket,
key: archiveFile,
contentType: contentType,
expression: expression,
completionHandler: completionHandler
).continueWith { (task) -> Any? in
if let error = task.error as NSError? {
print("localizedDescription:\n\(error.localizedDescription)")
print("userInfo:\n\(error.userInfo)")
}
if let _ = task.result {
// Do something with uploadTask.
}
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment