I am trying to make a request to a PHP server from my swift app. For some reason php is showing an empty array as the $_REQUEST variable. I have looked through stack overflow and implemented everything I can find that might help, but still getting an empty array in php. Here is the relevant swift code...
func connect(_ pin: String, completion: #escaping(Result<ConnectResponse?, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(
ConnectResponse(success: (res["success"] == "true"), connect_id: res["connect_id"] ?? nil, error: res["error"] ?? nil)))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
print(String(data: self.request.httpBody!, encoding: .utf8))
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
That sends the request to the server, the setup for the request is in the static var setup...
private static var sharedConnector: ApiConnector = {
let url = URL(string: "https://mywebsiteURLhere.com/api/mobile/challenge")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request)
return connector
}()
So I have the right header values for application/json I have the request method set to post, I am base64encoding the json data and in PHP I have the setup getting php://input...
$rawRequest = file_get_contents("php://input");
and dumping the $_REQUEST variable to an error log, but I always get array\n(\n)\n
it is just showing an empty array
I even did
error_log("Raw request from index.php");
error_log(print_r($rawRequest, true));
and it logs a completely empty line.
I can't figure out why PHP is getting nothing in the request, from everything I have seen online I am doing the request correctly in swift. Any help is really appreciated. Thank you
As per your Swift Code, Can you please replace the following method.
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData)
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
You need to replace this line let body = Data(jsonData) with
let body = Data(jsonData).base64EncodedData()
Without seeing your PHP code, it is difficult to determine the entire picture. However, whatever steps you perform to encode your data via the client (Swift) you must reverse to successfully decode the message on the server.
For example, if you prepare and send the request from your client as follows.
Client:
JSON encode data
base-64 encode
send data
The your server must reverse the steps to successfully decode the data.
Server:
recv data
base-64 decode data
JSON decode data
Unless your server requires it, I would remove the base-64 encode step, as it only complicates your encode / decode process.
I have created a working example: https://github.com/stuartcarnie/stackoverflow/tree/master/q59329179
Clone it or pull down the specific code in your own project.
To test, open up a terminal and run the php server:
$ cd q59329179/php
$ php -S localhost:8080 router.php
PHP 7.3.9 Development Server started at Thu Dec 19 10:47:58 2019
Listening on http://localhost:8080
Document root is /Users/stuartcarnie/projects/stackoverflow/q59329179/php
Press Ctrl-C to quit.
Test it works with curl in another terminal session:
$ curl -XPOST localhost:8080 --data-binary '{"string": "foo", "number": 5}'
Note you should see output in the php session:
[Thu Dec 19 11:33:43 2019] Array
(
[string] => foo
[number] => 5
)
Run the Swift test:
$ cd q59329179/swift
$ swift run request
Note again, decoded output in php session:
[Thu Dec 19 11:20:49 2019] Array
(
[string] => string value
[number] => 12345
[bool] =>
)
Your request is probably not arriving through the POST structure, but is kept in the request body.
Try running this as your first PHP operation:
$raw = file_get_contents('php://input');
and see what, if anything, is now into $raw. You should see a Base64 encoded string there, that you need to decode - like this, if you need an array:
$info = json_decode(base64_decode($raw), true);
I've tested your code and it's working fine. The issue might be at your PHP end. I've tested the following code on local server as well as on httpbin
The output from a local server (recent version of XAMPP (php 7.3.12)):
Sending request with thw following variables
eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
result eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
message ["additional_info": "13.2.2", "mobile_pin_connect": "1234", "device_info": "iPhone"]
Code:
ApiConnector.swift
import Foundation
import UIKit
class ApiConnector{
var request: URLRequest
private init(request: URLRequest) {
self.request = request
}
public static var sharedConnector: ApiConnector = {
let url = URL(string: "http://localhost/post/index.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request: request)
return connector
}()
func connect(_ pin: String, completion: #escaping(Result<Dictionary<String, String>, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(res))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
print("result \(stringResult)")
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let session = URLSession.shared
override func viewDidLoad() {
super.viewDidLoad()
ApiConnector.sharedConnector.connect("1234") { (result) in
switch result {
case .success(let message):
print("message \(message)")
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
index.php
echo file_get_contents("php://input");
You can verify your code by doing a request to https://httpbin.org/post
output:
Sending request with thw following variables
eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==
result {
"args": {},
"data": "eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-us",
"Content-Length": "108",
"Content-Type": "application/json; charset=utf-8",
"Host": "httpbin.org",
"User-Agent": "SessionTest/1 CFNetwork/1120 Darwin/19.0.0"
},
"json": null,
"origin": "122.173.135.243, 122.173.135.243",
"url": "https://httpbin.org/post"
}
in else block
If you are running an older version of PHP then You might need HTTP_RAW_POST_DATA
Have look at this SO for more info on PHP side.
I'm currently on a project where I have to submit some data to PHP file and get the return from PHP.
Problem
When I try to do that using iOS URLSession, I'm getting an error,
The data couldn’t be read because it isn’t in the correct format.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Because of this error, I made a sample php file where I return the value which I sent from Swift. And still getting this error along with some additional information.
<NSHTTPURLResponse: 0x60400042e200> { URL: http://192.168.1.99/insertDataTest.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 5;
"Content-Type" = "application/json";
Date = "Thu, 07 Dec 2017 09:55:58 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Raspbian)";
} }
What I've done so far
Here I know the content coming from the PHP, cannot be read by Swift.
I'm sending a 5 digit string from Swift to PHP and since I'm returning it without doing anything, I'm getting length of 5 data. Also I manually added a code to php in orders to made header as application/json. But still getting this error. I'm sending json encoded data from PHP as well.
My Code
Swift:
let postParameters = "{\"usermobilenum\":12345}"
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
{
print(response!)
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)
}
}
task.resume()
PHP :
<?php
header("Content-Type: application/json");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$data =json_decode(file_get_contents('php://input'),true);
$userPhone = $data["usermobilenum"];
echo json_encode($userPhone);
mysqli_close($connect);
}
else
{
echo json_encode("Failed in POST Method");
}
?>
I have no idea what this causes. I did try to find a solution for this in the internet and had no luck. Please help here. I'm using the latest Swift version.
Luckily I found the solution for my own problem. I missed to understand the error. As it says "option to allow fragments not set.", What I did was adding option .allowFragments. So the whole line after this replacement,
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
And I could solve the problem and get the answer PHP returns.
so I'm trying to create managed stripe accounts with PHP Swift and Alamofire. But it's not working at all.
Here's my PHP code:
<?php
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("My APIKEY");
$country = $_POST['country'];
$create = \Stripe\Account::create(array(
"country" => $country,
"managed" => true
)
);
?>
Here's my swift code:
#IBAction func createBtn(_ sender: Any) {
let card = STPCardParams()
card.number = "5200828282828210"
card.expMonth = 4
card.expYear = 2024
card.cvc = "242"
card.currency = "usd"
STPAPIClient.shared().createToken(withCard: card ,completion: {(token, error) -> Void in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
else if let token = token {
print(token)
self.createUsingToken(token:token)
}
})
}
func createUsingToken(token:STPToken) {
let requestString = "My request URL"
let params = ["token": token.tokenId, "country": "US"]
//This line of code will suffice, but we want a response
Alamofire.request(requestString, method: .post, parameters: params).responseJSON { (response) in
print("REQUEST: \(response.request!)") // original URL request
print("RESPONSE: \(response.response!)") // URL response
print("DATA: \(response.data!)") // server data
print("RESULT: \(response.result)") // result of response serialization
if let JSON = response.result.error {
print("JSON: \(JSON.localizedDescription)")
}
}
}
And I'm getting this error from Alamofire: JSON: Response could not be serialized, input data was nil or zero length.
Thanks for your help.
It looks like your Swift/Alamofire request is expecting a JSON response, but your PHP code is not sending any response at all: you're sending an account creation request to Stripe but then never outputting any data.
You likely want to prepare an array with the attributes that you expect in your Swift code, then output it as JSON at the end of your PHP script:
echo json_encode($result);
I am having trouble using URLSession to access JSON data generated by a PHP file.
I am both confused about the Swift 3 syntax and the completion handlers.
So far I have:
override func viewDidLoad() {
super.viewDidLoad()
var data : NSMutableData = NSMutableData()
let urlString: String = "http://seemeclothing.xyz/service.php"
let urlObject: URL = URL(string: urlString)!
let response = URLResponse
let config = URLSessionConfiguration.default
let sessionObject: URLSession
sessionObject.dataTask(with: urlObject) { (Data?, URLResponse?, Error?) in
print(data)
print(URLResponse)
print(Error)
}
sessionObject.resume()
}
I want sessionObject to go to my server and print JSON data from PHP file.
Any help would be greatly appreciated.
I would strongly suggest using Alamofire. It abstracts away all the tedious stuff in URLSession. I switched to this a few days ago and am a happy camper since then.
For your problem:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
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.