how to upload image in swift 2 to php server - php

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)
}
`

Related

Swift 3 - Displaying images from mySQL database in newsfeed

So I'm in the middle of designing a social media application that displays posts, comprised of a picture and a description, on a newsfeed. I am able to upload posts to our database, however, I am having problems pulling the image from the database. Specifically, I am getting an error around the code
let image = post["path"] as! UIImage
Saying:
"Thread 1: signal SIGABRT", while the compiler says "Could not cast
value of type '__NSCFString' to 'UIImage'."
Here's the entirety of my code:
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var activities = [AnyObject]()
var images = [UIImage]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell
let post = activities[indexPath.row]
print(post["path"])
let image = post["path"] as! UIImage
let username = post["username"] as? String
let text = post["text"] as? String
cell.titleLbl.text = text
cell.userLbl.text = username
cell.activityImage.image = image //as! UIImage
//cell.dateLbl.text = activities[indexPath.row]
//cell.activityImage.image = images[indexPath.row]
DispatchQueue.main.async {
}
return cell
}
override func viewWillAppear(_ animated: Bool) {
loadActivities()
}
func loadActivities() {
let id = user!["id"] as! String
let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&text=&uuid="
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// clean up
self.activities.removeAll(keepingCapacity: false)
self.images.removeAll(keepingCapacity: false)
//self.tableView.reloadData()
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.activities = posts
for i in self.activities.indices {
print("printed")
let path = self.activities[i]["path"] as? String
if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
if let imageData = try? Data(contentsOf: url) {
if let image = UIImage(data: imageData) {
self.images.append(image)
print(self.images)
}
}
}
/*
if path != "" {
//let url = URL(string: path!)!
let url = URL(fileURLWithPath: path!)
let imageData = try? Data(contentsOf: url)
//let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
*/
else {
let image = UIImage()
self.images.append(image)
}
}
self.tableView.reloadData()
} catch {
}
} else {
}
})
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NSMutableData {
func appendString(_ string : String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
If there is anything you think I should do to improve or make the code run correctly, please let me know!

Swift 3 - Pulling images from mySQL database

I am currently in the process of designing an application that has a newsfeed. Images and text are stored in our database but I am having trouble pulling the image and displaying it. The code I have should work but I am getting a fatal error saying "THREAD 1: EXC_BAD_INSTRUCTION" around
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
and the compiler displays this message - "fatal error: unexpectedly found nil while unwrapping an Optional value".
I'm getting the error in this snippet of code:
if!path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
} else {
let image = UIImage()
self.images.append(image)
}
Being very new to programming, I've been stuck on this for quite a while now. If there is anything you suggest, let me know! Thanks!
Also, the photo I am trying to retrieve is a .jpg, not sure if that may be important.
(Here's the rest of the code if it is needed)
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var activities = [AnyObject]()
var images = [UIImage]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell
let post = activities[indexPath.row]
let image = images[indexPath.row]
let username = post["username"] as? String
let text = post["text"] as? String
cell.titleLbl.text = text
cell.userLbl.text = username
cell.activityImage.image! = image
//cell.dateLbl.text = activities[indexPath.row]
//cell.activityImage.image = images[indexPath.row]
return cell
}
override func viewWillAppear(_ animated: Bool) {
loadActivities()
}
func loadActivities() {
let id = user!["id"] as! String
let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&text=&uuid="
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// clean up
self.activities.removeAll(keepingCapacity: false)
self.images.removeAll(keepingCapacity: false)
self.tableView.reloadData()
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.activities = posts
for i in 0 ..< self.activities.count {
let path = self.activities[i]["path"] as? String
if !path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
} else {
let image = UIImage()
self.images.append(image)
}
}
self.tableView.reloadData()
} catch {
}
} else {
}
})
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NSMutableData {
func appendString(_ string : String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
Why are you doing all of this ? Get the URLs of the images from your server and then load them asynchronously in cellForRowAtIndexPath using SDWebImage. It is a library you can find it here. https://github.com/rs/SDWebImage. This way you won't need to store your images in an array and it will be faster to load.
Or you can also implement your own async loading of images.
you could try something like this to avoid runtime errors:
if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
if let imageData = try? Data(contentsOf: url) {
if let image = UIImage(data: imageData) {
self.images.append(image)
}
}
}
instead of this
if!path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
}

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;
}

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