以编程方式而不是硬编码方式引用AWS S3存储桶名称 [英] Referencing AWS S3 bucket name programmatically instead of hardcoded

查看:100
本文介绍了以编程方式而不是硬编码方式引用AWS S3存储桶名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与AWS Amplify合作开发iOS应用程序.我已经通过S3添加了存储空间以托管一些资产,并正在尝试配置该应用程序以下载它们.唯一的问题是,我看到的每个示例都对存储桶名称和路径进行了硬编码,但是因为我有多个环境,有时会创建新环境,并且每个存储桶都附加了环境名称,所以我不必重写存储桶每次都命名.

I'm working with AWS Amplify to develop an iOS application. I've added storage through S3 to host some assets and am trying to configure the application to download them. The only issue is that every example I see has the bucket name and path hardcoded, but because I have multiple environments and make new environments sometimes and each bucket has the environment name appended to it, I don't want to have to rewrite the bucket name each time.

例如,如果我在测试环境中,则存储桶名称可能是assetxxxxxx-test,但是如果我切换到新环境,则可能是在引用assyyyyy-dev.

For example if I'm in my test environment the bucket name might be assetsxxxxxx-test but if I switch to a new environment, I might be referencing assetsyyyyy-dev let's say.

问题是在aswconfiguration.json文件中引用了存储桶名称:

The thing is the bucket name is referenced in the aswconfiguration.json file:

"S3TransferUtility": {
    "Default": {
        "Bucket": "assetsxxxxx-test",
        "Region": "us-east-2"
    }
}

所以我的问题是我该如何以编程方式引用该存储桶名称,以便在切换环境时重写该字段时,不必更改代码.

So my question is how can I reference that bucket name programmatically so that when that field is rewritten when I switch environments, I won't have to change my code.

谢谢

推荐答案

我解决了.令其他人感到疑惑的是,我仍然不确定AWS开发工具包是否内置了一个字段,但我决定将awsconfiguration.json文件直接解析为自定义结构:

I solved it. For anybody else wondering, I'm still not sure if there's a field built in to the AWS SDK, but I decided to parse the awsconfiguration.json file directly int a custom struct:

struct AWSConfigurationJSON: Codable{
    let S3TransferUtility: S3TransferUtility
}

struct S3TransferUtility: Codable{
    let Default: S3TransferUtilityDefault
}

struct S3TransferUtilityDefault: Codable{
    let Bucket: String
    let Region: String
}

然后我读取文件并解析JSON.

and then I read the file and parsed the JSON.

if let path = Bundle.main.path(forResource: "awsconfiguration", ofType: "json") {
            do{
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let jsonResult = try JSONDecoder().decode(AWSConfigurationJSON.self, from: data)
                print(jsonResult.S3TransferUtility.Default.Bucket)
                bucketPath = jsonResult.S3TransferUtility.Default.Bucket
            }catch let e{
                print("error \(e)")
                bucketPath = ""

            }
        }else{
            bucketPath = ""

        }

这篇关于以编程方式而不是硬编码方式引用AWS S3存储桶名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆