Invalid JSON require Swift iOS - php

I am developing a simple iOS Swift app. I want to make a log-in screen for my app that will connect to already existing user database in Wordpress. I found some PHP scripts and Swift code.
I am trying to post username and login, check it and return the result(isUser = true/false or 1/0)
Here is a PHP script
<?php
// Read request parameters
$username= $_REQUEST["username"];
$password = $_REQUEST["password"];
// Store values in an array
$returnValue = array("username"=>$username, "password"=>$password);
// Send back request in JSON format
echo json_encode($returnValue);
?>
and a Swift function
func getPHPJson() {
let urlPath: String = "LINK_TO_PHP_FILE?username=\(user)&password=\(pass)"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do
{
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
{
print(jsonResult)
//print(jsonResult["isUser"] as! Bool)
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString!)")
}
} catch let error as NSError
{
print(error.localizedDescription)
print("error")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
})
}
it gives me a desired result.
OUTPUT
{
password = iosappusettest1;
username = iosappusettest;
}
raw response: {"username":"iosappusettest","password":"iosappusettest1"}
But when I add function to check if user is registered - I always get an invalid JSON
here is PHP function
function authentication ($user, $pass){
global $wp, $wp_rewrite, $wp_the_query, $wp_query;
if(empty($user) || empty($pass)){
return 0;
} else {
require_once('../wp-blog-header.php');
$status = 0;
$auth = wp_authenticate($user, $pass );
if( is_wp_error($auth) ) {
$status = 0;
} else {
$status = 1;
}
return $status;
}
}
I believe the problem is require_once function. In raw response I get a lot of html tags and other data that make my JSON invalid.
Is there any way to clear the page and output in the JSON only? echo "<script> document.documentElement.innerHTML = ''; </script>"; in PHP did't help me. maybe jQuery will help?
Maybe I can check if user is registered in another way?
Maybe I can store my result in a separate place or temp file?
Maybe I should wrap my data not in JSON but something else?
So I need to pass username and password to PHP, check it with authentication function(that uses require_once) and send back the $status to iOS Swift app ass variable.
Question is answered.
The problem was in WP plugin, that redirected all unlogined users from all the links in that domain, so when i called require_once('../wp-blog-header.php'); i was always redirected to main page and that was the reason for wrong JSON file with all the HTML markup.

Keep your response in pure JSON, and leave out any html tags as they are not needed by your ios end.

Related

Trying to Parse JSON in swift but not working

I'm trying to parse some JSON, this is what it's returning when I directly go to the URL:
[{"Password":"whatever1"}]
My code is able to receive the data correctly (when I debugged the variable "data" had the above JSON) however when trying to Parse it, it won't work. I think it might have to do with the square brackets, cause I've been parsing other JSONs without the square brackets and it works well.
Here is my code:
func SignIn (username: String, password: String, completion: #escaping (Bool)->())
{
let url = URL(string: "http://<myIP>/API/SignIn.php?username=\(username)");
let task = URLSession.shared.dataTask(with: url!)
{ (data, response, error) in
if let data = data
{
do
{
// Convert the data to JSON
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
// print( jsonSerialized)
if let json = jsonSerialized, let result = json["Password"]
{
print(result)
if (String(describing: result) == password)
{
completion(true)
}
else
{
completion(false)
}
// TODO: password is wrong,
// TODO: username is wrong
// TODO: else if timeout
}
}
catch let error as NSError {
print(error.localizedDescription)
completion(false)
}
}
else if let error = error
{
print(error.localizedDescription)
completion(false)
}
}
task.resume()
}
Rewrite code to :
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]]
This is needed as your JSON response is an array of dictionaries, like the others have mentioned.
Access the result using:
let result = json.first["Password"]

Return Json from Php to Swift Alamofire

Hi guys i am using alamofire on a swift 3 iphone program, my problem is that i need to return a value from the php page my problem is that the value that comes back to me is this. How do I make sure that the value I return is: no prova#email.it
I hope I have explained
RETURN VALUE(NOT CORRECT):
SUCCESS: {
message = "no Optional(\"prova#email.it\")";
}
no Optional("prova#email.it")
SWIFT CODE:
import Foundation
import Alamofire
class User{
//URL to our web service
var email=""
var password=""
func PrintValue(){
// print(username);
//print(password);
}
func Login() -> String{
//var ris="";
var readvalue=""
let URLString = "http://localhost/test/login_mobile.php"
let parameters_value: Parameters = [
"email": email,
"password": password
]
//Sending http post request
Alamofire.request(URLString, method: .post, parameters: parameters_value).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
//displaying the message in label
readvalue = (jsonData.value(forKey: "message") as! String?)!
print(readvalue)
}
}
return readvalue
}
}
PHP CODE:
<?php
include 'user.php';
header('Content-Type: application/json');
$email= $_POST['email'];
$password = $_POST['password'];
$ris['message']="";
$user = new User();
//procedo con il login
if($user->login($email,$password,"MOBILE")==true){
$ris['message']="yes";
}
else{
$ris['message']="no $email";
}
echo json_encode($ris);
?>
I think it can be done something like:
if let readvalue = jsonData.value(forKey: "message") as? String {
print(readvalue)
}
must print wihtout Optional
Just did this in a playground and it works as expected..
import UIKit
let response: [AnyHashable: Any] = [
"message": "hello world"
]
class MyCoolClass {
func login() {
var readvalue = ""
let jsonData = response as NSDictionary
readvalue = jsonData.value(forKey: "message") as! String
debugPrint("the readvalue is: \(readvalue)")
}
}
let instance = MyCoolClass()
instance.login()
This will print: "the readvalue is: hello world"
The code is not very failsafe...
You need to use nil coalescing to make your value non-optional. e.g. print(readvalue ?? "nil"). Something better would be reengineer your response handling to properly return a typed value or a specific error.

POST data from iOS to php server always NULL - iOS 10, Swift 3, php

i am implementing a FCM app server and wanted to store the device registration token id into my own database (Server written in PHP).
I realise the data in device id token is always null, Can someone point the right way to store the token accordingly into database?
Really appreciated perhaps someone could guide me on this issue, thanks!
Kindly refer the code/screenshots below:-
AppDelegate.swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
Callquery(token)
}
AppDelegate.swift (Callquery method which send a POST request to server side script)
func Callquery(_ token: String)
{
// append parameter to oneDictionary
let tokenString = ["token": token] as [String: Any]
// create the request
var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php")!)
// set the method as POST
request.httpMethod = "POST"
// append the paramter to body
request.httpBody = try! JSONSerialization.data(withJSONObject: tokenString, options: [])
// create the session
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
if error != nil {
print("There was error during datatask session")
print(error)
} else {
do {
guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }
guard let errors = json?["errors"] as? [[String: Any]] else { return }
if errors.count > 0 {
// show error
print("There is an error during parse JSON datatask")
return
} else {
// show confirmation
print("datatask with JSON format performed successfully")
}
}
}
print(request)
}).resume()
}
Service Side Script(registerToken.php):
<?php
include 'config.php';
$token = $_POST['token'];
$sql = "INSERT INTO users (email,device_id) VALUES ('email','$token')";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
Running App with real devices log as below:-
Database users table (device id always has nothing):-
users table structure:-
tokenString :-
I had solved this issue by using GET method instead of POST method as below:-
Appdelegate.swift :
var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php?token=\(token)")!)
Server side script :
$token = $_GET['token'];

Submitting properly escaped JSON to PHP in a POST request with Swift

I have been struggling to get a web service to work with a native Swift application when a user is attempting to upload data using the "&" character, amongst others.
After various attempts at escaping the request, I am at a loss and looking for some advice to solving this. I have included a some code from both the Swift application and the PHP scripts for reference. The data is able to be posted to the server (I am using FileMaker Server PHP API), but not when the "&" is included in a user-submitted value as the JSON is being cut short when PHP hits that character.
The postData argument in the Swift request sample is a dictionary in JSON format, which is encoded using the below code from JSONStringify:
func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
let options = NSJSONWritingOptions.PrettyPrinted
if NSJSONSerialization.isValidJSONObject(value) {
do {
let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
} catch {
return ""
}
}
return ""
}
Swift Request
class func returnAnyObject (phpFile:String, postData:String) -> AnyObject? {
let server:String = "http://myserver.com"
let url = NSURL(string: "\(server)\(phpFile)")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)
request.HTTPMethod = "POST"
// set data
let dataString = postData.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
do {
let reply: NSData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
if let results = NSString(data:reply, encoding:NSUTF8StringEncoding) {
return results
} else {
return nil
}
} catch {
return nil
}
}
PHP
Below is the relevant portion of the PHP script. Perhaps there is some step I am missing with this as well?
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$req1 = '../../FileMaker.php';
$req2 = '../../FM_Connect.php';
require_once $req1;
require_once $req2;
//set fixed variables
$layout = 'php_Lineitems';
//Define passed variables
$json = $_POST['json'];
$json = stripslashes($json);
$fieldArray = json_decode($json); // This is now an associative array
?>
Don't put the JSON as a string, you don't need to stringify it, should be of NSData type.
Then you set that in the body of your request directly.
Note on the PHP side you won't be able to access $_POST['json'].
You will need to change your code to:
$json = json_decode(file_get_contents('php://input'));

How can I get a PHP variable over to swift [duplicate]

This question already has answers here:
How to make HTTP request in Swift?
(21 answers)
Closed 8 years ago.
I want a variable in php to get over in swift (or get the value for the variable). How can I do that?
$name = "William";
How can I get this string "William" to my Swift script? Can anyone help me?
I know it's something with JSON and POST or something but otherwise I am complete lost.
When you want to get data from PHP to an iOS device, I would recommend having the PHP code send it as JSON. JSON is easier for the the client app to parse (especially as your web service responses get more complicated) and it makes it easier to differentiate between a valid response and some generic server error).
To send JSON from PHP, I generally create an "associative array" (e.g., the $results variable below), and then call json_encode:
<?php
$name = "William";
$results = Array("name" => $name);
header("Content-Type: application/json");
echo json_encode($results);
?>
This (a) specifies a Content-Type header that specifies that the response is going to be application/json; and (b) then encodes $results.
The JSON delivered to the device will look like:
{"name":"William"}
Then you can write Swift code to call NSJSONSerialization to parse that response. For example, in Swift 3:
let url = URL(string: "http://example.com/test.php")!
let request = URLRequest(url: url)
// modify the request as necessary, if necessary
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let name = json["name"] {
print("name = \(name)") // if everything is good, you'll see "William"
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
Or in Swift 2:
let url = NSURL(string: "http://example.com/test.php")!
let request = NSMutableURLRequest(URL: url)
// modify the request as necessary, if necessary
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: String], let name = json["name"] {
print("name = \(name)") // if everything is good, you'll see "William"
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
}
task.resume()
I'm answering this as an iOS/PHP dev rather than a Swift programmer.
You need to send an HTTP request to the webserver hosting the PHP script, which will return the contents of the web page given any specified parameters.
For example, if you sent an GET HTTP request to the following PHP script, the response would be "William" in the form of NSData or NSString depending on the method you use.
<?php
$name = "William";
echo $name;
?>
With a parameter GET http://myserver.com/some_script.php?name=William:
<?php
$name = $_GET['name']; // takes the ?name=William parameter from the URL
echo $name; // William
?>
As to the Swift side of things, there is a perfectly valid answer here which denotes one of the myriad methods of sending a request: https://stackoverflow.com/a/24016254/556479.

Categories