Balbas Code

SwiftUIでS3へアップロードする

公開日: 2023-10-22 22:32:27
更新日: 2023-10-23 00:42:18

SwiftUIでS3へアップロードするコードをアップしておきます。
こちらはアンドロイド版と違い、ファイルもContentViewのみでOKで、結構すんなりいけました。
(podfileだけは使っております。)

ContentView


import SwiftUI
import AWSS3

struct ContentView: View {
var body: some View {
Button("Upload File") {
uploadFile()
}
}

func uploadFile() {
// AWS設定
let accessKey = "AKIASW3RRIEJRTMMMAWL" // ここに実際のアクセスキーを入力
let secretKey = "Fm/AwrKh6JW4FDLvYpyl5tWG0xLi8PYVIiVR/eC+" // ここに実際のシークレットキーを入力

// エンドポイントの作成
guard AWSEndpoint(urlString: "https://s3.amazonaws.com") != nil else {
print("Invalid endpoint URL")
return
}

// 東京リージョンを指定
let configuration = AWSServiceConfiguration(region: .APNortheast1,
credentialsProvider: AWSStaticCredentialsProvider(accessKey: accessKey,
secretKey: secretKey))
// サービス設定を適用
AWSServiceManager.default().defaultServiceConfiguration = configuration

// 空のファイルを作成
guard let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Document directory could not be found")
return
}

let newFileURL = documentDirectory.appendingPathComponent("empty.txt")

let emptyString = ""
do {
try emptyString.write(to: newFileURL, atomically: true, encoding: .utf8)
print("New file created at: \(newFileURL)")
} catch {
print("Error creating new file: \(error)")
return // ファイル作成に失敗した場合、ここで処理を停止
}

// S3の設定
let s3BucketName = "balbas2"
let s3UploadKeyName = "empty.txt" // これはファイル名またはパスのような構造です

// ファイルをアップロード
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadFile(newFileURL, bucket: s3BucketName,
key: s3UploadKeyName,
contentType: "text/plain",
expression: nil) { (task, error) in

if let error = error {
print("Error: \(error.localizedDescription)")
return
}

if task.status == .completed {
print("Uploaded successfully.")
}
}
}
}



保存結果


Android版を作成する前にSwiftUI版でテストしていたので、リージョンや、バケット名、アクセスキー、シークレットアクセスキー、エンドポイント等のワードやら設定やらがどのように必要になってくるのかわかったので、とてもよかったです。