How can I tell when data has been received with NSURLConnection? - php

I'm working on a Swift application that uses a PHP web service to query a database. One issue - I have no idea how to tell when data has been received in the model class, so I can't update the view! How can I tell if the connection has finished, then update said view? For this purpose, I've created a dummy label called text. Thanks for the help in advance, and happy holidays!
User.swift
import Foundation
class User: NSObject {
var firstName: String?
var lastName: String?
var username: String
var password: String
var email: String?
var recievedJSON: NSMutableData = NSMutableData()
var userData: [[String: String]]!
var verified: Bool = false
required init(username: String, password: String) {
self.username = username
self.password = password
}
init(firstName: String, lastName: String, username: String, password: String, email: String) {
self.firstName = firstName
self.lastName = lastName
self.username = username
self.password = password
self.email = email
}
func attemptRegister() {
var variables: [String] = ["firstname=" + self.firstName! + "&"]
variables.append("lastname=" + self.lastName! + "&")
variables.append("username=" + self.username + "&")
variables.append("password=" + self.password + "&")
variables.append("email=" + self.email!)
request("https://codekaufman.com/register.php", variables: variables)
}
func attemptSignIn() {
var variables: [String] = ["username=" + self.username + "&"]
variables.append("password=" + self.password)
request("https://codekaufman.com/login.php", variables: variables)
println("Attempting sign-in...")
}
private func request(urlPath: String, variables: [String]?) {
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
if(variables != nil) {
request.HTTPMethod = "POST"
var bodyData: NSString = ""
for item in variables! {
bodyData = bodyData + NSString(string: item)
}
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
}
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
println("Connection started.")
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.recievedJSON.appendData(data)
println("Possible data recieved.")
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
userData = parseJSON(recievedJSON)
if(userData != nil) {
println("Data recieved:")
println(userData[0])
self.firstName = userData[0]["first_name"]
self.lastName = userData[0]["last_name"]
} else {
println("No data recieved.")
}
}
func parseJSON(inputData: NSData) -> [[String: String]]? {
var error: NSError?
var userData: [[String: String]]!
userData = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [[String: String]]
#if DEBUG
if (userData != nil) {
println("NSData had data, printing and returning.")
println(userData)
} else {
println("NSData empty, returning nil.")
}
#endif
return userData
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBAction func prepareForUnwind(seque: UIStoryboardSegue) {
}
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var text: UILabel!
#IBAction func signin(sender: AnyObject) {
if(username.text == "" || password.text == "") {
var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
var attempt: User = User(username: username.text, password: password.text)
attempt.attemptSignIn()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Edit: Based on previous comments/answers, I feel I should clarify. Data is being received. But it takes a few seconds, so how can I signify to the view controller that the data has been received, and the process is finished?

You can add a notification in the view controller with:
func addObserverForName(_ name: String?, object obj: AnyObject?, queue queue: NSOperationQueue?, usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol
Be sure to remove it in deinit:
func removeObserver(_ notificationObserver: AnyObject)
Send the notification from connectionDidFinishLoading using:
func postNotificationName(_ notificationName: String, object notificationSender: AnyObject?, userInfo userInfo: [NSObject : AnyObject]?)

Related

How to make the response from server automatically shown on the textview (outlet3) when the register button is clicked

So now when the user input the id and password and hit the register button.
it will then submit to a php script that return a response.
The issue is right now i could get the response from php script only after i clicked on the textfield.
I am trying to make the response automatically shown on the textview (outlet3) when the register button is clicked.
import UIKit
var id00 = ""
var pw00 = ""
var result = ""
var response = ""
class SecondViewController: UIViewController {
#IBOutlet weak var outlet: UITextField!
#IBOutlet weak var outlet2: UITextField!
#IBOutlet weak var outlet3: UITextField!
//register button
#IBAction func action(_ sender: Any) {
//get id &pw
id00 = outlet.text!
pw00 = outlet2.text!
//imie
let deviceUUID: String = (UIDevice.current.identifierForVendor?.uuidString)!
let myUrl = URL(string: "http://192.168.0.152/testing00/user/reg.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "employeeid=" + id00 + "&password=" + pw00 + "&imie=" + deviceUUID ;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
if let data = data {
let string = String(data: data, encoding: String.Encoding.utf8)
self.outlet3.text = string
print(self.outlet3.text!) //
}
print("response = \(request)")
}
task.resume()
}
}
replace this code:-
self.outlet3.text = string
With this code:-
DispatchQueue.main.async {
self.outlet3.text = string
}

When calling PHP service from Swift for iOS 9, results don't display

I'm new to Swift and trying to set up an iOS app. At the start of the app I'm dropping a pin on the map and sending the location to my php web service. Then after the next 10 iterations through the map movement, another pin is to be dropped and the location gets sent to the service. Looking at the database everything is getting to the service and is getting loaded to the tables. But, the first time calling the service is the only time that the response data can be retrieved.
Here's the view controller:
//
// ViewController.swift
// Tracker
//
// Created by Kendall Crouch on 2/6/16.
// Copyright © 2016 KLC Computing. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var places = [Dictionary<String, String>()]
var hasStarted: Bool = false
var locationCount = 0
var routeId: NSInteger = -1
var lastStep: NSInteger = -1
var markerId: Int = -1
var manager:CLLocationManager!
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var lblLatitude: UILabel!
#IBOutlet weak var lblLongitude: UILabel!
#IBOutlet weak var btnStartControl: UIBarButtonItem!
#IBOutlet weak var btnPauseControl: UIBarButtonItem!
#IBOutlet weak var btnStopControl: UIBarButtonItem!
#IBAction func btnStart(sender: AnyObject) {
btnStartControl.enabled = false
btnPauseControl.enabled = true
btnStopControl.enabled = true
manager.startUpdatingLocation()
}
#IBAction func btnPause(sender: AnyObject) {
manager.stopUpdatingLocation()
self.btnStartControl.enabled = true
self.btnPauseControl.enabled = false
hasStarted = false
}
#IBAction func btnStop(sender: AnyObject) {
manager.stopUpdatingLocation()
self.btnStopControl.enabled = false
self.btnStartControl.enabled = true
hasStarted = false
}
override func viewDidLoad() {
super.viewDidLoad()
locationCount = 500
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationCount += 1
let userLocation:CLLocation = locations[0]
let latitude: CLLocationDegrees = userLocation.coordinate.latitude
let longitude: CLLocationDegrees = userLocation.coordinate.longitude
lblLatitude.text = String(userLocation.coordinate.latitude)
lblLongitude.text = String(userLocation.coordinate.longitude)
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: false)
let newCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let newLocation = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
if locationCount > 10 {
hasStarted = false
locationCount = 0
}
if !hasStarted {
hasStarted = true
CLGeocoder().reverseGeocodeLocation(newLocation) { (placemarks, error) -> Void in
var title = "Added on \(NSDate())"
if error != nil {
print(error)
}
else {
if let p = placemarks?[0] {
let formattedAddressLines = p.addressDictionary?["FormattedAddressLines"] as! NSArray
title = formattedAddressLines.componentsJoinedByString(", ")
}
}
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
annotation.title = title
self.mapView.addAnnotation(annotation)
self.places.append(["name":title, "lat":"\(newCoordinate.latitude)", "lon":"\(newCoordinate.longitude)"])
NSUserDefaults.standardUserDefaults().setObject(self.places, forKey: "places")
let url: NSURL = NSURL(string: "http://tracker.klccomputing.com/updateRoute.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodyData = "routeId=\(self.routeId)&routeName=\(title)&routeDate=\(NSDate())&lastStep=\(self.lastStep)&latitude=\(newLocation.coordinate.latitude)&longitude=\(newLocation.coordinate.longitude)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
print(data)
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let jsonData = json {
print("KLCA\(jsonData)")
if let newRouteId: NSInteger = jsonData["routeId"] as? NSInteger {
self.routeId = newRouteId
if let newLastStep: NSInteger = jsonData["lastStep"] as? NSInteger {
self.lastStep = newLastStep
print("KLCB\(self.lastStep)")
}
}
}
}
catch {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
}
}
})
task.resume()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Console information. I let the app run 3 iterations. The first time through the variable if statement to get the information from the variable jsonData worked. The second and third times through, they didn't work:
Optional(<7b22726f 75746549 64223a31 362c226d 61726b65 72496422 3a36312c 226c6173 74537465 70223a31 7d>)
KLCA{
lastStep = 1;
markerId = 61;
routeId = 16;
}
KLCB1
Optional(<7b22726f 75746549 64223a22 3136222c 226d6172 6b657249 64223a36 322c226c 61737453 74657022 3a327d>)
KLCA{
lastStep = 2;
markerId = 62;
routeId = 16;
}
Optional(<7b22726f 75746549 64223a22 3136222c 226d6172 6b657249 64223a36 332c226c 61737453 74657022 3a327d>)
KLCA{
lastStep = 2;
markerId = 63;
routeId = 16;
}

how to upload image in swift 2 to php server

I am trying to upload photos to my database in my server from my iPhone app. the language I am using is swift 2. please help me. I am attaching my code to upload the other details to the JSON link and I want to add image also to my link. please help me
import UIKit
class MealViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var ratingControl: RatingControl!
#IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
let attributes = [
NSForegroundColorAttributeName: UIColor.blueColor(),
NSFontAttributeName: UIFont(name: "Avenir", size: 2)!
]
self.navigationController?.navigationBar.titleTextAttributes = attributes
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
print("my image ", photoImageView)
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
//nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1) {
self.performSegueWithIdentifier("goto_login", sender: self)
} else {
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}
#IBAction func ratingSubmitButton(sender: UIButton) {
print(ratingControl.rating)
print(self.usernameLabel.text!)
let name:NSString = self.usernameLabel.text!
let value = ratingControl.rating
let imageData = UIImagePNGRepresentation(photoImageView.image!)
do {
let post:NSString = "name=\(name)&value=\(value)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://kiran.com/insert.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData);
//var error: NSError?
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[#"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Login SUCCESS");
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(name, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.performSegueWithIdentifier("goto_rating", sender: self)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Failed"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
}
} else {
}
} catch {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Success!"
alertView.message = "Thank You"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
#IBAction func logOutButton(sender: UIButton) {
let appDomain = NSBundle.mainBundle().bundleIdentifier
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)
self.performSegueWithIdentifier("goto_login", sender: self)
}
`

HTTP Post Request check in swift

i have php file to check a value passed from swift ios, i print json data, this is the code:
<?php
$said = $_REQUEST['sa_id'];
if($said == '123456') {
$returnValue = array("said" => "true");
}else{
$returnValue = array("said" => "false");
}
echo json_encode($returnValue);
?>
Also i wrote a swift function to check the returned said value, my code is work success in second click, i want it from first click:
class ViewController: UIViewController {
var saidResult = false;
#IBOutlet var saidField: UITextField!
#IBOutlet var labelField: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
}
#IBAction func checkSAID(sender: UIButton) {
if ( isValidSAID(saidField.text) == false ) {
labelField.text = "SAID is Invalid"
} else {
labelField.text = "Done"
}
}
func isValidSAID(said2Test: String) -> Bool {
let myUrl = NSURL(string: "http://*****.com/said.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "sa_id=\(said2Test)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) in
if error != nil {
println("error=\(error)")
return
}
// You can print out response object
println("response = \(response)")
// Print out response body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
if let parseJSON =myJSON {
// Now we can access value of First Name by its key
var saidValue = parseJSON["said"] as? String
println("saidValue: \(saidValue)")
if ((saidValue) == "true" ) {
self.saidResult = true;
}
println("saidResult: \(self.saidResult)");
}
}
task.resume()
println("saidResult: \(self.saidResult)");
if ( self.saidResult == true ){
return true
} else {
return false
}
}
}
As i say, in first click the value of saidResult is false but after that it is take the true value
How i can solve this issue, or is there another way to improve my code?
I think this is probably because the http request is not answered on the first click but is on the second click.
you could try replacing your checkSAID function with this.
#IBAction func checkSAID(sender: UIButton) {
let saidQueue = dispatch_queue_create("saidQueue", DISPATCH_QUEUE_CONCURRENT)
// Do the checking on a background thread.
dispatch_async(saidQueue, {
if ( isValidSAID(saidField.text) == false ) {
// As the UI updates are performed on the main queue, update the label on the main queue.
dispatch_async(dispatch_get_main_queue()) {
labelField.text = "SAID is Invalid"
})
} else {
dispatch_async(dispatch_get_main_queue()) {
labelField.text = "Done"
})
}
})
}
Finally, after 4 days of testing i solved my problem.
I changed isValidSAID function code:
func isValidSAID(said2Test: String) -> Bool {
var status: String = "";
let myUrl = NSURL(string: "http://*****.com/said.php?sa_id=\(said2Test)");
let data = NSData(contentsOfURL: myUrl!)
let json = NSHSONSerialization.JSONObjectWithData(data!, option: nil, error: nil) as! NSDictionary
status = (json["said"] as? String)!
println(status)
return ( status == "true" ) ? true : false
}
and solved my issue.

POST request in NSMutableURLConnection returns nil, whereas the same GET request works fine

I've been working on an iOS program, and I'm having a few issues. I had recently been testing a simple system to login using the GET method, but I need to use POST for security, so I switched over. The error is on the 'if let dictionary' line, and the error is that it is trying to unwrap a nil optional. Although it has the exact same data, it still does not work. Ideas? Thanks in advance.
iOS:
class ViewController: UIViewController {
var json: NSMutableData = NSMutableData()
var data: [[String: String]]!
#IBOutlet weak var usernameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBAction func attemptLogin(sender: UIButton) {
if(usernameTextField.text == "" || passwordTextField.text == "") {
var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
attemptConnection(usernameTextField.text, password: passwordTextField.text)
}
}
func parseJSON(inputData: NSData) -> [[String: String]]{
var error: NSError?
var dictionary: [[String: String]]!
if (inputData.length != 0) {
if let dictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [[String: String]] {
} else {
}
}
return dictionary
}
override func viewDidLoad() {
super.viewDidLoad()
var tapBackground: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard:")
tapBackground.numberOfTapsRequired = 1;
self.view.addGestureRecognizer(tapBackground)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func dismissKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
func attemptConnection(username: String, password: String){
let urlPath: String = "https://codekaufman.com/getusers.php"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let bodyData = ("username=" + usernameTextField.text + "&password=" + passwordTextField.text as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = bodyData
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
activityIndicator.startAnimating()
self.view.userInteractionEnabled = false
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.json.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
activityIndicator.stopAnimating()
self.view.userInteractionEnabled = true
data = parseJSON(json)
println(data.count)
if(data.count != 0) {
self.performSegueWithIdentifier("login", sender: self)
println(data[0])
println(data[0]["first_name"]!)
} else {
self.view.backgroundColor = UIColor.redColor()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "login") {
var svc = segue.destinationViewController as SecondViewController;
svc.data = self.data
}
}
}
PHP:
try {
$dbh = new PDO('mysql:host=localhost; dbname=codeggdj_users', $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$recievedUsername = $_POST['username'];
$recievedPassword = $_POST['password'];
$sth = $dbh->prepare('SELECT password FROM users WHERE username = ?');
$sth->execute([$recievedUsername]);
if($sth->rowCount()) {
$row = $sth->fetch(PDO::FETCH_OBJ);
if(password_verify($recievedPassword, $row->password)) {
$sth = $dbh->prepare('SELECT id, username, first_name, last_name FROM users WHERE username = ?');
$sth->execute([$recievedUsername]);
echo json_encode($row = $sth->fetchAll(PDO::FETCH_ASSOC));
} else {
echo 'Incorrect Password';
}
} else {
echo 'Incorrect Username';
}
} catch(PDOException $e) {
echo $e->getMessage();
}

Categories