我在应用程序中使用Microsoft的翻译器API,并使用以下代码生成访问令牌:

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函数,然后尝试按以下方式访问访问令牌:

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

let accessToken = accessTokenObject[0].value

print(accessToken)


但是我得到这个错误:


  由于未捕获的异常“ RLMException”而终止应用程序,原因:“索引0超出范围(必须小于0)”


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

最佳答案

这段代码正在快速地工作以获取令牌:

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 - Swift Realm'RLMException',原因:“索引0超出范围(必须小于0),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45352693/

10-10 16:11