Swift Realm' RLMException',原因:'索引0超出范围(必须小于0)

时间:2017-07-27 13:46:40

标签: swift realm microsoft-translator

我在我的应用中使用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函数没有创建访问令牌,但我不明白为什么。

1 个答案:

答案 0 :(得分:0)

此代码正在使用swift代码来获取令牌:

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
}