我正在研究学生系统项目。所有服务器端都已完成,但iOS客户端应用程序遇到了麻烦。
我正在尝试为用户创建登录页面,而不是检查数据库中的信息是否正确
以下是代码:
import Foundation
import UIKit
class LoginPage: UIViewController {
/*A reference to the username/student ID text field*/
@IBOutlet weak var idField: UITextField!
//A reference to the password field
@IBOutlet weak var passwordField: UITextField!
//Send the information from the text fields to the server
@IBAction func loginButtonTapped(_ sender: UIButton) {
//declare parameter as a dictionary which contains string as key and value combination.
var parameters = ["name": idField.text!, "password": passwordField.text!] as Dictionary<String, String>
//create the url with NSURL
let url = NSURL(string: "https://api.sis.kemoke.net")
//create the session object
var session = URLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = JSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
}
对我而言,这一切看起来都不错,但我收到了错误 “无法调用函数URLSession” 和 错误处理程序的“额外参数”。
我该如何解决这个问题?