我正在使用具有登录屏幕的应用程序,这对我来说是第一次。在关注了为此提供教程的不同网站之后,我创建了一个LoginService ViewController,它将有助于登录该应用程序。
以下是我在此ViewController中使用的代码的一部分:
// 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
我已经知道Swift 2.0处理的错误与我以前的错误不同。我知道这个版本的Swift使用try,let和catch代码来处理错误。我的问题是我之前没有使用过这些类型的代码,也不确定如何在这种情况下使用它们。
答案 0 :(得分:1)
在iOS 7和后者NSJSONSerialization是线程安全的。现在你可以使用do try catch
斯威夫特3:
do{
let JsonDict = try JSONSerialization.jsonObject(with: data, options:.MutableLeaves)
}
catch let error as NSError {
print(error)
}
Swift 2:
do{
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! [String:AnyObject]
}catch let error as NSError{
print(error)
}
答案 1 :(得分:0)
JSONObjectWithData
函数需要您提到的do
try
catch
语法,因为其声明网站上的方法标有throws
关键字。 (此处有文档:https://developer.apple.com/reference/foundation/jsonserialization/1418059-jsonobject)
不要简单地使用它。
do {
try someMethodWhichCanThrow()
catch(error) {
// maybe log the error here
}
这在Swift编程语言书中有所描述:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508