I have this error
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
here is my swift code:
var exercise:String = ""
for value in numberOfExercisesArray{
exercise = exercise + value.text! + ","
}
if exercise.characters.last == ","{
exercise.removeAtIndex(exercise.endIndex.predecessor())
}
the string i want to post (exercise) is in the this context : "bench press,5,100"
However I cant get this string to go through because of the error above
Below is how i connect to my php/sql server:
let myURL = NSURL(string: "http://localhost:8888/saveWorkout.php");
let request = NSMutableURLRequest(URL:myURL!);
request.HTTPMethod = "POST";
let postString = "exercise=\(exercise)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let parseJSON = json{
let resultValue = parseJSON["status"] as! String!;
print("result: \(resultValue)")
if(resultValue == "Success"){
print("worked")
}
else{
print("not worked")
}
}
}
catch { print(error) }
}
task.resume();
How do I fix this error
Thanks
Your problem is , Your are using Json , and when you try to parse json actually you are not parsing it perfectly, Json can parse as Dictionary or Array , , check your json response try to decode it in any online json parser , to see how it's look like,
copy your server response (json)
search in google ( online json formatter )
past it there and see
Related
Hi all I am trying my hands on Swift and I am trying to post users registration data. I know how to do it firebase but my main project is in php mysql so I want to connect it with swift
#IBAction func signUp(_ sender: Any) {
//check textfield data
checkTextFields()
//create user
let url = NSURL(string: "http://localhost:8888/helo/register.php")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
//apending body to url
let body = "Fullname=\(name.text!.lowercased())&userName=\(userName.text!.lowercased())&emailAddress=\(emailAddress.text!.lowercased())&password=\(password.text!.lowercased())"
request.httpBody = body.data(using: String.Encoding.utf8)
//lunching
URLSession.shared.dataTaskWithRequest(request as URLRequest, completionHandler: { (data:NSData?, response:URLResponse?, error:NSError?) in
if error == nil{
dispatch_async(dispatch_get_main_queue(),{
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as?
NSDictionary
guard let parseJSON = json else{
print("Error while parsing")
return
}
let id = parseJSON["id"]
if id != nil {
print(parseJSON)
}
}catch{
print("Caugth an error: \(error)")
}
})
}else{
print("error: \(error)")
}
} )
}
I am getting an error on the line where I have commented as as lunching which say
Cannot convert value of type '(NSData?, URLResponse?, NSError?) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'
I am new to Swift any help is welcome thank you all. I am using Xcode 9
After enough reading, I just realised I was doing a very tedious and using orthodox method when things have improved. I removed the whole code and did everything with Alamofire. Its really easy and straight forward. I will post the code below to help others who encounter similar problems later on.
//Constant that holds the URL for our web servicer
let URL_USER_REGISTER = "http://localhost:8888/members/register.php?"
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON{
response in
//printing response
print(response)
//getting 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
self.lableMessage.text = jsonData.value(forKey: "message") as! String?
}
}
you have to first import Alamofire.
I'm trying to send data from Swift to PHP but whatever i try, it won't work. The latest error i'm getting is the
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."' and
'UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}' errors.
I have no idea where the problem is, as i validated my JSON and the PHP side is working when using Postmen. So the problem has to be in the Swift code i guess..
This is my Swift code:
let payload = try! JSONEncoder().encode(bon)
let payloadString = String(data:payload, encoding: .utf8)!
//URL to our web service
let URL_SAVE_TEAM = URL(string:"http://trinto.kuppeveld.xyz/API/createteam.php")
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: URL_SAVE_TEAM!)
//setting the method to post
request.httpMethod = "POST"
//adding the data to request body
request.httpBody = payloadString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error is \(error!)")
return;
}
print("-----")
print(String(data: data!, encoding: String.Encoding.utf8)!)
print("-----")
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print(msg)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
When i print payloadString it returns the JSON as following:
{"datum":"11-12-2017","winkel":"jumbo","producten":[{"prijs":"2.50","naam":"ham"},{"prijs":"1.20","naam":"brood"}],"tijd":"15:07"}
And to be sure, here is my PHP code (which works with Postmen, as i mentioned):
$json = file_get_contents('php://input');
$array = json_decode($json, true);
echo $json;
var_dump($array);
var_dump($array) return NULL for some reason, but when i use Postmen it has no problem giving back the JSON as i inserted.
Has anybody got a clue how to fix my problem? Thanks in advance!
I am trying to create an iOS app using Swift and I need to implement a search feature using UISearchbar. It takes in a store name and searches for it in the database to return an array of store names. Below is the segment of the code which is giving me some errors. I followed this website closely http://swiftdeveloperblog.com/case-insensitive-search-with-swift-php-and-mysql/
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
return
}
doSearch(searchWord: searchBar.text!)
}
func doSearch(searchWord: String){
mysearchBar.resignFirstResponder()
let myURL = NSURL(string: "http://localhost:8080/searchStore.php")
var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler:{ (data: Data?, response: URLResponse!, error: Error!) -> Void in
DispatchQueue.main.async() {
if error != nil{
self.displayAlertMessage(userMessage: error.localizedDescription)
return
}
do{
var _: Error?
//STOPPED HERE AS OF NOW
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
self.results.removeAll(keepingCapacity: false)
self.tableView.reloadData()
if let parseJSON = json{
if let stores = parseJSON["stores"] as? [AnyObject]{
for storeOjb in stores{
let name = (storeOjb["name"] as! String)
self.results.append(name)
}
self.tableView.reloadData()
}else if(parseJSON["message"] != nil){
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil){
self.displayAlertMessage(userMessage: errorMessage!)
}
}
}
} catch {
print(error)
}
}
})
task.resume()
}
I get 2 errors the first one is due to mysearchBar.resignFirstResponder(). The app terminates and I keep getting
"fatal error: unexpectedly found nil while unwrapping an Optional value"
The second error is when I remove mysearchBar.resignFirstResponder() I get
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo=
{NSDebugDescription=No value.}
UPDATE:
I fixed the 2nd problem by entering this line
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
However, it seems that my postString variable is facing a problem
breakpoint check photo
You should set a breakpoint on the line that is giving you the error by clicking on the line number and run the program. Look for nil values by using the bottom left debugger pane window.
This will help you find what value is nil and if you already know what variable is nil please tell us!
I have a very similar problem like in Why the http post request body always wrapped by Optional text in the Swift app
but I can´t apply the solution from this thread to my code, because I don´t have a request.setValue.
Does anyone know what I need to do to get rid of the Optional?
My Code:
#IBAction func LoginButtonTapped(sender: UIButton) {
let username = UsernameTextField.text
let password = PasswordTextField.text
if(username!.isEmpty || password!.isEmpty) {return; }
let request = NSMutableURLRequest (URL: NSURL(string: "http://myip/loginregister.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
let data = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
let success = json["success"] as? Int // Okay, the `json` is here, let's get the value for 'success' out of it
print("Success: \(success)")
} else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) // No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
You must unwrapping the value when get text from UITextField first, because the text property of UITextField allow nil
let username = UsernameTextField.text!
let password = PasswordTextField.text!
Explain more
When you unwrap the text of the UITextField, the username and password will be not nil variable.
The code compare empty should be:
if(username.isEmpty || password.isEmpty) {return }
If you does not unwrap, when you use this "\(username)", your are try to convert a nilable object to string, so the string result will be appended with a "Optional" text.
To Solve problem with Content-Type for request
Paste this line to your code. I don't believe that you do not have setValue method.
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
I'm having trouble parsing a JSON, sent from a PHP script, on IOS using swift. I just started learning IOS development this week and also had never worked with JSON before so any help would be greatly appreciated on parsing this correctly. I'm sending a result from a mysql query as a JSON to the app. Here is my swift code and the error log in which you can see the object received by the http service.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let secondViewController:VC2 = segue.destinationViewController as! VC2
let myUrl = NSURL(string: "myscriptaddress");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "condition=" + String(currentval);
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
secondViewController.mystring = "getting ready"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Success")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error can't parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
And now the error log:
Error could not parse JSON: Optional([{"unidad":"sanfrancisco","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"pediatricouniversitario","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"sanjorge","capacidad":"15","uso":"7","telefono":"num"},{"unidad":"himacaguas","capacidad":"20","uso":"4","telefono":"num"},{"unidad":"himabayamon","capacidad":"20","uso":"8","telefono":"num"},{"unidad":"sanlucas","capacidad":"10","uso":"8","telefono":"num"},{"unidad":"auxiliomutuo","capacidad":"15","uso":"11","telefono":"num"}])
Its failing to unwrap the JSON data as a dictionary type. The JSON string provided is an array of objects.
Try this in your JSONObjectWithData call:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String : AnyObject]]