swift 3 with Mysql - php

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

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

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

Return json value with php from swift iOS

Hello I have a small a problem with the code below, Xcode print this error:
ERROR: json error: Error Domain=NSCocoaErrorDomain Code=3840 "No
value." UserInfo={NSDebugDescription=No value.}
SWIFT CODE:
let yourUrl=“mylink.php”
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL!)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
let dataString = "Email=\(Email.text)&Password=\(Password.text)"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()
PHP CODE:
mylink.php
<?php
header("Content-Type: application/json");
$email = $_POST["Email"];
$password = $_POST["Password"];
$stat=“myvalue”;
return json_encode($stat);
?>
How can I solve this error?

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