gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:16:44 25 4
gpt4 key购买 nike

我在我的应用程序中使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com