Xcode 8.3 get data from php and json - php

I'm trying to make a small program, that send a username to a web data base. and get the name, status, point of the user.
i have fund out how to send the username, and get the json output.
it look like this: {"name":"gert","status":"0","point":"20"}
and this is my php code
<?php
header('Content-type: application/json');
ob_start();
session_start();
mysql_connect("host","username","password");
mysql_select_db("dbname") or die("Unable to select database");
$qrcode = $_POST['username'];
$result = mysql_query("SELECT * FROM qrcode WHERE qrcode = '$qrcode' ");
$pic_name = mysql_fetch_array($result);
$myObj = new \stdClass();
$myObj->name = $pic_name['name'];
$myObj->status = $pic_name['status'];
$myObj->point = $pic_name['point'];
$myJSON = json_encode($myObj);
echo $myJSON;
ob_end_flush();
?>
and this is my swift code
import UIKit
class ViewController: UIViewController {
let url_to_request:String = "http://www.hholm.dk/time_app/gertqrcode.php"
override func viewDidLoad() {
super.viewDidLoad()
download_request()
}
func download_request()
{
let url:URL = URL(string: url_to_request)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "username=200"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.downloadTask(with: request as URLRequest, completionHandler: {
(
location, response, error) in
let urlContents = try! NSString(contentsOf: location!, encoding: String.Encoding.utf8.rawValue)
guard let _:NSString = urlContents else {
print("error")
return
}
print(urlContents)
})
task.resume()
}
}
and now i have to extract the json, (i think its called)
I would like to have the name, status and point, as some ting i can use i the rest of the program.

try it.
If you have any questions let me know, I hope I have helped!
import Foundation
import UIKit
class getJSON: NSObject, URLSessionDataDelegate
{
//properties
var data : NSMutableData = NSMutableData()
func downloadItems(user:String)
{
let url = NSMutableURLRequest(url: NSURL(string: "http://192.168.1.102:8888/test/test.php")! as URL)
url.httpMethod = "POST"
let postString = "a=\(user)"
url.httpBody = postString.data(using: String.Encoding.utf8)
print(url.httpBody = postString.data(using: String.Encoding.utf8))
var session: URLSession!
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url as URLRequest)
task.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
self.data.append(data as Data);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if error != nil
{
print("Not Found", error ??)
}
else
{
print("Ok")
self.parseJSON()
}
}
func parseJSON()
{
var jsonResult: NSArray = NSArray()
do
{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
print("jsonResult.count",jsonResult.count)
}
catch let error as NSError
{
print("jsonResult: ", error)
}
var jsonElement: NSDictionary = NSDictionary()
var contador = 0
for i in (0..<jsonResult.count)
{
jsonElement = jsonResult[i] as! NSDictionary
if let nameUser = jsonElement["name"] as? String,
let pointUser = jsonElement["point"] as? String,
let statusUser = jsonElement["status"] as? String
{
print("Name: ", nameUser)
print("Status: ", statusUser)
print("Point: ", pointUser)
}
}
}
}
Try this in your php, I'm showing you how I made it work for me, it will need to change as you wish, I'm passing this code as an example.
<?php
header('Content-type: application/json');
ob_start();
session_start();
mysql_connect("host","username","password");
mysql_select_db("dbname") or die("Unable to select database");
$qrcode = $_POST['username'];
$query="SELECT name,status,point FROM qrcode WHERE qrcode = '$qrcode'";
$resultset = mysql_query($query, $connection);
$data = array();
while ($row = mysql_fetch_assoc($resultset))
{
$data[] = $row;
}
//echo '<pre>',print_r($data),'</pre>';
echo json_encode($data);
ob_end_flush();
?>
In your viewcontroller:
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
print("Status: ",getStatusUSer)
}
#IBAction func get(_ sender: Any)
{
let userName = "charles"
let getUser = getJSON()
getUser.downloadItems(user:userName)
}
//Your Code...
}

Related

Data does not being sent to Database because it cannot be read

I'm working on a project where I need to send some data to the remote database. So I'm developing an iOS app using Swift 3.1 and when I try to send data to the database it says,
The data couldn’t be read because it isn’t in the correct format.
Also there is another error;
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
This is my swift code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure
{
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = "{\"usermobilenum\":\(String(describing: userMobileNumber!)),\"contactnum\":\(contact.phoneNumber!)}";
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in
if error != nil
{
print("error is \(String(describing: error))")
return;
}
do
{
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = myJSON
{
var msg : String!
msg = parseJSON["message"] as! String?
print(msg)
}
}
catch
{
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
This is my PHP in remote database:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
require 'connectDB.php';
$userPhone = $_POST["usermobilenum"];
$contactNum = $_POST["contactnum"];
$query = "SELECT * FROM user WHERE UserMobNum='".$userPhone."'"; // Usermobile is registered.SIP exists.
if($results= mysqli_query($connect,$query))
{
if(mysqli_num_rows($results)>0)
{
$i=0;
while($rows=mysqli_fetch_assoc($results))
{
$sip[$i] = $rows["SIP"];
$i++;
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
else
{
$availableSIP=false;
while($availableSIP==false) // Assign a random value until it's being a valid one.
{
$sip[0]=rand(1,9999);
$queryToCheck = "SELECT * FROM user WHERE SIP='".$sip[0]."'";
if($results= mysqli_query($connect,$queryToCheck))
{
if(mysqli_num_rows($results)==0)
{
$availableSIP=true;
}
}
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
}
else
{
echo "First Level Failure!";
die(mysqli_error($connect));
}
mysqli_close($connect);
}
else
{
echo "Failed in POST Method"
}
?>
What I did
Went through all of stack overflow and other site suggestions but had no luck. I even checked my jSon string using a json validator and it passed. This is how my jSon string looks like.
{"usermobilenum":1234567890,"contactnum":9345}
However after some search I found that this happens because Remote database PHP sends this error message. So I checked each and every variable in PHP but couldn't find any problem. Also this couldn't be a problem with PHP cause I work with those exact php files when I connect to via my android app. That works fine. But in iOS it generates that error. Can someone help me please?
UPDATE
This is insertdataTest.php file:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$userPhone = $_POST["usermobilenum"];
echo $userPhone;
mysqli_close($connect);
}
else
{
echo json_encode("Failed in POST Method");
}
?>
{"usermobilenum":1234567890,"contactnum": 9345} - this is treated as a String. It's not a VALID JSON.
Updated code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure {
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = NSMutableDictionary()
postParameters["usermobilenum"] = userMobileNumber
postParameters["contactnum"] = contact.phoneNumber!
let jsonData = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error is \(String(describing: error))")
return;
}
do {
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
if let parseJSON: NSMutableDictionary = NSMutableDictionary(dictionary: myJSON as! NSMutableDictionary){
let msg = parseJSON["message"] as! String
print(msg)
}
}
catch {
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
Buddy I debug you code and found that there is error in server response not in you code. try this and reply me ASAP please
before this line "let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary"
add "let str = String.init(data: data!, encoding: .utf8)
print(str ?? "error")"
I am waiting please.

Get Parameters in php file when POST from Swift

I'm trying to get parameters in my php file when I'm posting from SWIFT (login file)
This is my php file :
<?
$json = array();
$json['username'] = $_POST['username'];
$json['password'] = $_POST['password'];
$json['result'] = "false";
$json['id_familia'] = 148;
$json['id_centre'] = 2;
$json['web'] = "www.cec-escolalolivar.cat";
echo json_encode($json);
?>
This is swift code (of course I've tried with different options, sync, not sync, ....)
let url : NSURL = NSURL(string: "http://www.cec-info.cat/app/config.inc.main_families_json.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
let bodyData="data=xgubianas#gmail.com"
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response,data,error) in
print (response as Any)
if let data = data{
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print (json)
}
catch
{
print (error)
}
}
}

swift 3 with Mysql

I am trying to make registration in swift3 with mysql
but there is some thing wrong ,
when I run my app and make register return msg "some fields are empty"
In php code:
$fullname = htmlentities($_REQUEST["fullname"]);
$username = htmlentities($_REQUEST["username"]);
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$phone = htmlentities($_REQUEST["phone"])
swift code:
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://localhost/php/register.php?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "fullname=\(FirstName.text)%20\(LastName.text)&username=\(UserName.text)&email=\(Email.text)&password=\(Password.text)&phone=\(Phone.text)"
request.httpBody = body.data(using: String.Encoding.utf8)
let task = session.dataTask(with: url!) {data, response, error in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print(json)
}
} catch {
print("error in JSONSerialization")
}
}
}
task.resume()
I think you missed this
let task = session.dataTask(with: request) {data, response, error in
replace url with request

Error in Swift JSON when receiving 'json_encode' from PHP script. Works fine without it

I have a Swift function for a button that when pressed writes some details into a database via PHP:
#IBAction func createCommunityButtonTapped(_ sender: AnyObject) {
let communityName = communityNameTextField.text;
if (communityName!.isEmpty){
displayMyAlertMessage(userMessage: "You must name your Community");
return;
}else{
func generateRandomStringWithLength(length: Int) -> String {
var randomString = ""
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for _ in 1...length {
let randomIndex = Int(arc4random_uniform(UInt32(letters.characters.count)))
let a = letters.index(letters.startIndex, offsetBy: randomIndex)
randomString += String(letters[a])
}
return randomString
}
let communityCode = generateRandomStringWithLength(length: 6)
passwordTextField.text = communityCode
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}
}
task.resume()
}
}
The function works great apart from whenever I add this echo jsonline into the PHP script:
if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
echo json_encode($returnValue);
return;
}
Then I get an error Thread 8: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subside = 0x0) on this line:
if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}
And in the debug area the following details
data Data? some
response URLResponse? 0x0000618000223500
error Error? nil none
I think I'm missing a line, or need to set a variable to the JSONSerialization instead of 'try!' but I'm very unsure what.
You are returning null. Try this
if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
return json_encode($returnValue);
}

IOS SWIFT 2 - Http Post json array to server

I want to send data from my iOS app to a PHP sever in JSON format. I am doing this at the backend with the following code:
$json = $_POST['json'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
I want to send data in a JSON variable such that I can accept the data in
the JSON variable and then extract the fields one by one.
At the moment, I am doing this in my iOS app with the following Swift code:
func login(){
let email:NSString = txtEmail.text!
let password:NSString = txtPassword.text!
let post:NSString = "username=\(email)&password=\(password)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://example.com/test.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);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
let success:NSInteger = jsonData!.valueForKey("success") as! NSInteger
NSLog("Success: %ld", success);
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}
I think I have to send a JSON array, but I don't know how can I save the variables in the array and send the JSON array to the PHP server. Anyone have any ideas?
You can do this by creating an array of dictionaries:
var user_outer_arrary = [[String:Any]]()
var user_inner_array = [String: Any]();
var jsonData : Data? = nil
let user_data :[String:Any]=["email": email,"password": password];
user_outer_arrary.append(user_data);
user_inner_array=["json": user_outer_arrary]
Then convert to JSON:
do
{
jsonData = try JSONSerialization.data(withJSONObject: user_inner_array, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch
{
}

Categories