我正在開發一個應用程序,它具有登錄屏幕,這對我來說是第一個。在遵循爲此提供的教程的不同網站之後,我製作了一個LoginService ViewController,它可以幫助您登錄應用程序。Xcode - Swift 2.0:通過NSJSONSerialization調用「額外參數」錯誤
下面是我在這個視圖控制器使用的代碼的一部分:
// MARK: Private Methods
private func exchangeTokenForUserAccessTokenWithCompletionHandler(username: String, password: String, completion: (OAuthInfo?, error: String?) ->()) {
let path = "/oauthfake/token/"
let url = ConnectionSettings.apiURLWithPathComponents(path)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var params = "client_id=\(ConnectionSettings.clientId)&client_secret=\(ConnectionSettings.clientSecret)&grant_type=password&login=\(username)&password=\(password)"
var err: NSError?
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if (err != nil) {
// Something went wrong, log the error to the console.
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Something went wrong: '\(jsonStr)")
completion(nil, error: err?.localizedDescription)
} else {
if let parseJSON = json {
if let token = parseJSON.valueForKey("access_token") as? String {
if var issuedAt = parseJSON.valueForKey("issued_at") as? String {
if var tokenExpiresIn = parseJSON.valueForKey("expires_in") as? String {
if var refreshTokenIssuedAt = parseJSON.valueForKey("refresh_token_issued_at") as? String {
if let refreshToken = parseJSON.valueForKey("refresh_token") as? String {
if var refreshTokenExpiresIn = parseJSON.valueForKey("refresh_token_expires_in") as? String {
if let refreshCount = parseJSON.valueForKey("refresh_count") as? String {
let epochIssuedAt:Double = (issuedAt as NSString).doubleValue/1000.0
let epochRefreshTokenIssuedAt:Double = (refreshTokenIssuedAt as NSString).doubleValue/1000.0
let oauthInfo = OAuthInfo(issuedAt: epochIssuedAt, refreshTokenIssuedAt: epochRefreshTokenIssuedAt, tokenExpiresIn: (tokenExpiresIn as NSString).doubleValue, refreshToken: refreshToken, token: token, refreshTokenExpiresIn: (refreshTokenExpiresIn as NSString).doubleValue, refreshCount: (refreshCount as NSString).integerValue)
completion(oauthInfo, error: err?.localizedDescription)
我super.init似乎做工精細(上面沒有特色),以及該代碼的休息這個文件,但我得到一個錯誤的閱讀「額外的參數‘錯誤’呼叫」在這條線:
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
我已經收集是雨燕2.0處理錯誤不同,以什麼我已經習慣了。我知道這個版本的Swift使用try,let和catch代碼來查找錯誤。我的問題是我以前沒有使用過這些類型的代碼,並且不確定如何在這種特殊情況下使用它們。
感謝您的反饋意見,看看您如何佈置語法非常有幫助!如果可以問(我還在學習這個,對不起),我想確保我知道我應該把try try catch代碼與我在NSJSONSerialization錯誤中的行相比。 –
@ R.Osolinski:你想比較兩個NSJSONSerialization嗎? – Donal