The use of login page will be necessary when you limit the user access to you app for only registered users. In this tutorial we are going to post an http request to the server and get the response and process it.
You will have to create three php pages to handle the server side, you could collect the code for the php pages from my last ios post: Make an http request from the ios device using swift and also receiving a response as a json array from the server-side PHP Mysql.
You will have to create three php pages to handle the server side, you could collect the code for the php pages from my last ios post: Make an http request from the ios device using swift and also receiving a response as a json array from the server-side PHP Mysql.
Swift:
func post() {
var username="USERNAME" //replace with your username
var password="PASSWORD" //replace with your password
var session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "<The address to the login php page>")!)
request.HTTPMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = "&username=\(username)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(dataString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// checking whether JSONObjectWithData constructor return an error?
if(err != nil) {
println(err!.localizedDescription)
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonString)'")
}
else {
// checking for value in the response json
if let parseJSON = json {
// retrieving the parsed json data for the key 'success'
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// catching the error
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Something went wrong, Error could not parse JSON: \(jsonString)")
}
}
})
task.resume()
}
No comments:
Post a Comment