使用Alamofire验证HTTP请求(swift 3)

时间:2017-01-08 19:40:16

标签: ios json swift authentication alamofire

如何通过身份验证发出HTTP请求?在我的第一堂课中,我要求用户登录

       let url = "https://api.sis.kemoke.net/auth/login"
var parameters = ["email": "", "password": ""]
var token = ["X-Auth-Token": ""]

// Parameters textfields
@IBOutlet weak var email: UITextField?
@IBOutlet weak var password: UITextField?

// A method for the login button
@IBAction func loginButton(_ sender: UIButton) {
    parameters["email"] = email?.text //Read email from text field
    parameters["password"] = password?.text //Read password from text field
    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: token).responseJSON {
        (response) in
        print(response.response?.statusCode as Any)


        //Reading JWT authentication token from the server
        if let tokenString = response.result.value as? String {
            self.token["X-Auth-Token"] = tokenString
        }

        // manage alerts for different status codes
        if response.response?.statusCode == 401 {
            // present alert
            let alert = UIAlertController(title: "OOPS!", message: "Either username or password is wrong!", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        } else if response.response?.statusCode == 200 {
            self.performSegue(withIdentifier: "loginSegue", sender: nil)
        } else if (self.email?.text?.isEmpty)! || (self.password?.text?.isEmpty)! {
            let alert2 = UIAlertController(title: "HEY!", message: "You need to enter something!", preferredStyle: UIAlertControllerStyle.alert)
            alert2.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert2, animated: true, completion: nil)
        }
    }
}

用户输入正确的凭据后,我会转到用户可以选择选项的屏幕。 在这种情况下,当用户点击"课程"按钮它会切换到tableView,它应该显示特定于该用户的课程。

struct Courses {
    let course : String

    init(dictionary: [String:String]) {
        self.course = dictionary["course"] ?? ""
    }
}
   func downloadData() {
         Alamofire.request("https://api.sis.kemoke.net/student/course").responseJSON { response in
        print(response.request)  // original URL request
        print(response.response) // HTTP URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization

        //Optional binding to handle exceptions
        self.courseData.removeAll() // clean the data source array
        if let json = response.result.value as? [[String:String]] {
            for course in json {
                self.courseData.append(Courses(dictionary: course))
            }
            self.tableView.reloadData()
        }
    }
}

而不是将数据加载到数组中。 问题是我在控制台中收到以下错误

  Optional(https://api.sis.kemoke.net/student/course)
  Optional(<NSHTTPURLResponse: 0x608000228fc0> { URL:        https://api.sis.kemoke.net/student/course } { status code: 401, headers {
 "Access-Control-Allow-Headers" = "Accept, Origin, Content-type, X- Auth-Token";
"Access-Control-Allow-Method" = "Get, Post, Put, Delete, Options";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Type" = "text/plain; charset=utf-8";
Date = "Sun, 08 Jan 2017 20:31:21 GMT";
Server = "nginx/1.6.2";
"Set-Cookie" = "__NCTRACE=aff38563-adcb-457d-a592-9f61b255bcbe; path=/;  expires=Sun, 08-Jan-2017 21:01:21 GMT; HttpOnly";
"Transfer-Encoding" = Identity;
 } })
Optional(12 bytes)
FAILURE

我收到此错误,因为我没有进行身份验证。 我可以使用Alamofier的身份验证方法,但只有在我手动初始化变量(电子邮件和密码(。 那么如何使用已经登录的用户令牌来获取相关课程呢?

0 个答案:

没有答案