HTTP Post Request check in swift - php

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.

Related

How to fetch JSON data into UIPickerView in Swift 3.0 ?

My question is, how to fetch data from PHP into UIPickerView in Swift 3.0 ?
Currently, I have these code for UIPickerView to create dropdown list. Right now, I can only display the dropdown list value based on variable declare inside xcode var department = ["ICTD","FAD","PSD"]
dropdown.swift
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet var departmentLbl: UITextField!
#IBOutlet var dropdownLbl: UIPickerView!
#IBOutlet var outputLbl: UILabel!
#IBOutlet var user_idLbl: UILabel!
var department = ["ICTD","FAD","PSD"]
var user_id: String!
override func viewDidLoad() {
super.viewDidLoad()
user_id = "ID001" // these value that need to be past to PHP
let url = URL(string: "http://localhost/getdepartment.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let LoginDataToPost = "user_id=\(user_id!)"
request.httpBody = LoginDataToPost.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil { return }
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String] {
DispatchQueue.main.async {
let display = Int(json["display"]!)
let realname = json["real_name"]
let department = json["dept"]
if(display == 1) {
// dropdown list value display here
return
}
else { return }
}
}
else { }
}
catch {}
}
})
task.resume()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var countrows : Int = department.count
if pickerView == dropdownLbl {
countrows = self.department.count
}
return countrows
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == dropdownLbl {
let titleRow = department[row]
return titleRow
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == dropdownLbl {
self.departmentLbl.text = self.department[row]
self.dropdownLbl.isHidden = true
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == self.departmentLbl) {
self.dropdownLbl.isHidden = false
}
}
}
And I have these PHP code that gives an output of
real name and department
based on user_id value from x code
getdepartment.php
<?php
$connect = mysqli_connect("","","","");
global $connect;
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
$sql = "SELECT * FROM table WHERE user_id ='$user_id'";
$result = mysqli_query($connect,$sql);
if($result && mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
$real_namedb = $row['real_name'];
$dept_db = $row['dept'];
$output = array('real_name' => $real_namedb, 'dept' => $dept_db);
echo json_encode($output);
}
mysqli_free_result($result);
}
else { }
}
?>
These PHP gives an output of JSON data as below:
{"display":"1","real_name":"NAME TEST 1","dept":"ICTD"}
{"display":"1","real_name":"NAME TEST 2","dept":"ICTD"}
Appreciate if someone can help.
Thanks.
I believe you are supposed to create the dropdownlist based on values you received from server. Based on the code you've given in the question, I observed that you were not adding department names you got from the server to your array.
You can make following changes and observe:
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async
{
let display = Int(json["display"]!)
let realname = json["real_name"]
let departmentName = json["dept"]
if(display == 1) {
// dropdown list value display here
self.department.append(departmentName)
self.dropdownLbl.reloadAllComponents() // this is reference to your pickerView. Make it global and use it
return
}else { return }
}
}
Please let me know if it resolves the problem or not...

How to send data from Xcode 8 into PHP MySQL database?

I would like to ask on how to post the data from Xcode 8 into PHP MySQL database. Right now I have textField username and register button to triggered the function post.
Here's my code so far.
registerVC.swift
import UIKit
class RegisterVC: UIViewController {
#IBOutlet var usernametxt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func register_click(_ sender: Any) {
if usernametxt.text!.isEmpty{
usernametxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
else{
// Insert data into database
}
}
}
Register.php
<?php
$connect = mysqli_connect("", "", "", "");
global $connect;
if(isset($_POST['username']))
{
$username = $_POST['username'];
$insert = "INSERT INTO table (username)
VALUES ('$username')";
$run = mysqli_query($connect,$insert);
$response = array();
$response["success"] = true;
echo json_encode($response);
}
?>
In your else add sendData(usernametxt.text)
and add below function in your VC file
func sendData(username : String) {
var request = URLRequest(url: URL(string:"http://YOUR_WEBPAGE_ADDRESS")!)
request.httpMethod = "POST"
let postString = "name="+username
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
}
task.resume()

Read return value php on IOS application

Hello I'm writing an ios swift 3 application to communicate with a website, the app after doing a number of things should return a type value of false or true, but it does not happen you can tell me where I'm wrong and how to correct the mistake!
VALUE RETURN at swift:
....response = Optional( { URL: "http://....myurl.php"}.....
SWIFT CODE:
let myUrl = URL(string: "http://....myurl.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "username=James&password=Bond";
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=\(error)");
// return false
}
print("response = \(response)")
}
task.resume()
return 0;
PHP CODE:
include 'user.php';
$user = new User();
$username= $_REQUEST["username"];
$password = $_REQUEST["password"];
if($user->login($username,$password)==true){
echo json_encode("true");
}
else{
echo json_encode("false");
}
ERROR IMAGE:
You need to look into data and not response.
And maybe you should encapsulate your return value in your PHP code, like this for example:
if($user->login($username,$password)==true){
echo '{"success":true}';
}else{
echo '{"success":false}';
}
And then get the result in swift:
func login(request_completed:#escaping (_ succeded:Bool) -> ()) {
let myUrl=URL(string: "http://....myurl.php");
var request=URLRequest(url:myUrl!)
request.httpMethod="POST"
let postString = "username=James&password=Bond";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task=URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard data != nil else {
print("no data found")
request_completed(false)
return
}
do{
if let jsonData=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary{
print(jsonData)
let success=jsonData.value(forKey: "success") as! Bool
if success{
print("login succeded")
request_completed(true)
return
}else{
print("login failed")
request_completed(false)
return
}
}else{
print("could not parse json")
request_completed(false)
}
}catch{
print("request failed")
request_completed(false)
}
})
task.resume()
}

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

Categories