Swift Realm 'RLMException' ,原因 : 'Index 0 is out of bounds (must be less than 0)

标签 swift realm microsoft-translator

我在我的应用程序中使用 Microsoft 的翻译 API,并使用此代码生成访问 token :

func getAccessToken(){

    let key = "---"
    let requestUrl = URL(string: "https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
    var request = URLRequest(url: requestUrl!)
    request.httpMethod = "POST"
    request.addValue(key, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")

    let task = urlSession.dataTask(with: request) { (data, response, error) in
        guard let data = data, error == nil else{
            return
        }
        let token = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

        let realm = try! Realm()

        let accessToken = AccessToken()

        accessToken.value = token!

        try! realm.write {
            realm.add(accessToken)
        }
    }


    task.resume()
}

之后,我在 viewDidLoad 方法中使用 getAccessToken 函数,然后尝试像这样访问我的访问 token :

let realm = try! Realm()
let accessTokenObject = realm.objects(AccessToken.self)

let accessToken = accessTokenObject[0].value

print(accessToken)

但我收到此错误:

Terminating app due to uncaught exception 'RLMException', reason: 'Index 0 is out of bounds (must be less than 0)'

如何解决这个错误?我知道我的 getAccessToken 函数不会创建访问 token ,但我不明白为什么。

最佳答案

此代码正在使用快速代码来获取 token :

var azureToken = String()

//Method to get an Azure token.

func getAccessToken() -> String {

print("********get azure token selected********")

let azureKey = "xxxxxxxxxxxxxxxxxxxxxxx"
let postString = azureKey
let request = NSMutableURLRequest(url: URL(string: "https://api.cognitive.microsoft.com/sts/v1.0/issueToken" )!)

request.httpMethod = "POST"
request.addValue(postString, forHTTPHeaderField:"Ocp-Apim-Subscription-Key")

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    print("This is the data ********->", data as Any)
    print("This is the response ********->", response as Any)
    print("This is the error ********->", error as Any)

    if error != nil {
        print("error=\(String(describing: error))")

        return
    }

    let responseString = String(data: data!, encoding: .utf8)
    print("responseString = \(String(describing: responseString))")
    azureToken = responseString!

}

task.resume()

return azureToken
}

关于Swift Realm 'RLMException' ,原因 : 'Index 0 is out of bounds (must be less than 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352693/

相关文章:

ios - Google Mobile Native Express 广告 iOS - [AnyObject] 的问题

react-native - Realm for React Native 中纬度/经度最合适的数据类型是什么?

swift - Realm 重置模式版本

microsoft-translator - Microsoft Translator Text API 打破了 notranslate 跨度

c# - 使用 Microsoft Translator API 用 C# 翻译整个网页

ios - 将图像保存为本地文件或二进制数据 IOS

swift - 我如何知道 SwiftUI 按钮是否启用/禁用?

ios - Realm 将对象添加到列表中

android - Microsoft Translate 在我的 Android 应用程序中停止工作

ios - 单击导航 Controller 前的按钮时出现黑屏