i try to send value to server with this code by i have an error on this line:
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
the error is : EXTRA ARGUMENT IN CALL "error"
var yourUrl="mylink"
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "
V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "my value"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
if let dataFromString = results!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
if(json=="0"){
print("\n Dati non validi");
}
else{
print("\n Account creato");
}
}
You should never use sendSynchronousRequest as it is a blocking call. Also it is deprecated from iOS 9.0 onwards. Instead you can use NSURLSession. Try out following code
var yourUrl="mylink"
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)
var dataString = "my value"
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()
Related
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
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?
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
{
}
iam using swift function to send POST query to php script
func post_retJSON_inJSON(params : Dictionary<String, String>,tourl:String)
{
let myUrl = NSURL(string: tourl);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
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 firstNameValue = parseJSON["firstName"] as? String
println("firstNameValue: \(firstNameValue)")
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
task.resume()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
With this php
$firstName= $_POST["firstName"];
$lastName = $_POST["lastName"];
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);
// Send back request in JSON format
echo json_encode($returnValue);
AND then in swift i have a response
Optional({"firstName":null,"lastName":null})
I think i already try everything but I cant get in PHP parametres sended by SWIFT query. Help me please to figureout it!!!
solved with this php and the same swift as in top
// Read request parameters
$postdata = json_decode(file_get_contents("php://input"),TRUE);
$firstName= $postdata["firstName"];
$lastName = $postdata["lastName"];
// Store values in an array
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);
// Send back request in JSON format
echo json_encode($returnValue);
For my app i need to send a image to a php file.
I already know how to send strings using this:
var bodyData = "info=test"
let URL: NSURL = NSURL(string: "LINK TO A PHP FILE")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
And in my php file:
$info = $_POST['info'];
echo $info;
But i don't know how to send a image
var imageData :NSData = UIImageJPEGRepresentation(imagenReduced, 1.0);
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
let tempData = NSMutableData()
let fileName = filenames + ".jpg" //"prueba.jpg"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)
var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")
//check this code
func callToProfileUpdate()
{
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "Loading"
var userID: AnyObject! = NSUserDefaults.standardUserDefaults().valueForKey("USER_ID")
var urlString = NSString(string:"\(baseurl)action=update_profile&user_id=\(userID)&user_name=\(userName.text)&account_type=\(self.selectedAccountTypeLabel.text!)&show_comments=\(commentStauts)&tag_permission=\(tagPermission)")
urlString = urlString .stringByReplacingOccurrencesOfString(" ", withString: "%20")
var url = NSURL(string:urlString as String)
let urlRequest = NSMutableURLRequest(URL: url!)
if mediaData != nil
{
urlRequest.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
urlRequest.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"photo\"; filename=\".png\"\\.png\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(mediaData)
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
urlRequest.HTTPBody = body
}