How to resolve issue? I given description in body - ios

// Hi, i got response from url but getting error as below in title, please fix the issue.
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0
let Url = String(format: "http://www.fgndbdsn.in/index.php?route=api/mywebservices/addition")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["first" : "25", "second" : "25"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [[String:Any]]
print(json)
}catch {
print(error)
}
}
}.resume()

The response from the server must be valid JSON with a top level container which is an array or dictionary.

Related

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1. swift 4

I got response from api via postman
{
"status": "1",
"error": false,
"message": "Your order has been placed successfully"
}
I called api and pass the params which required to call api. The code is giving an error "Invalid value around character 1."
let urlsContainer = UrlsContainer()
let url = URL(string: urlsContainer.allotRunnerAPI)
let session = URLSession.shared
var request = URLRequest(url: url!)
let postString = "user_id=\(user_id)&pincode=\(pincode)&select_address=\(select_address)&store_id=\(store_id)"
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
The code should execute the do block of code
do {
let parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject]
print(parsedData)
}
but now because of some problem in code it is executing catch block of code
catch let error {
print(error)
}
})
task.resume()
I am not able to find the problem in my code to resolve the error
use [String:String] to send data to api
let params = ["user_id":user_id,
"pincode":pincode,"select_address":select_address,
"store_id":store_id]
let data = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
post this data as your body

Post request is not responding

I'm doing a very simple postRequest but I the service is not responding me, do you have any idea of why this is happening? maybe I'm doing something wrong could you help me? Thanks in advance.
Here is my code Request in postman
#IBAction func buton(_ sender: Any) {
let parameters = ["acceptPrivacyNotice": true, "name" :"xxxxx xxxxx", "email": "xxxxx#mail.com", "password":"Qwerty2012", "passwordConfirm":"Qwerty2012","deviceID" : "", "isProvider" : false, "idTypeProvider": 1] as [String : Any]
guard let url = URL(string: "https://www.apps-sellcom-dev.com/Engie/api/account/register") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("M1o2K1RVMzRHVSNteUtLOjNzSCR5LUEyKk5qOEhFRg==", forHTTPHeaderField: "Authorization")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("Response",response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
Try this:
#IBAction func buton(_ sender: Any){
let params = ["acceptPrivacyNotice": true, "name" :"xxxxx xxxxx", "email": "xxxxx#mail.com", "password":"Qwerty2012", "passwordConfirm":"Qwerty2012","deviceID" : "", "isProvider" : false, "idTypeProvider": 1] as [String : Any]
let session = Foundation.URLSession.shared
let url = URL(string: "https://www.apps-sellcom-dev.com/Engie/api/account/register")
var request = URLRequest(url : url!)
request.httpMethod = "POST"
do {
let jsonData = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.addValue("M1o2K1RVMzRHVSNteUtLOjNzSCR5LUEyKk5qOEhFRg==", forHTTPHeaderField: "Authorization")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
session.dataTask(with: request, completionHandler: { data, response, error in
OperationQueue.main.addOperation {
guard error == nil && data != nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString!)")
if let responsedata = responseString!.data(using: String.Encoding.utf8)! as? Data{
do {
let jsonResult:NSDictionary = try JSONSerialization.jsonObject(with: responsedata, options: []) as! NSDictionary
print("Get The Result \(jsonResult)")
if error != nil {
print("error=\(String(describing: error))")
}
if let str = jsonResult["success"] as? NSNull {
print("error=\(str)")
}
else {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Response string : \(String(describing: responseString))")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}) .resume()
}catch {
}
}
I've tested your code and the reason you are not seeing a response is that the completion block doesn't do anything in case of failure.
When I ran your request, it came back with the following error
Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error" UserInfo={NSErrorPeerAddressKey=<CFData 0x608000092200 [0x101840c70]>{length = 16, capacity = 16, bytes = 0x100201bb34bface50000000000000000}, _kCFStreamErrorCodeKey=100, _kCFStreamErrorDomainKey=1}
My best guess is that there is something wrong in the httpBody. Hope that helps.

JSON response format is incorrect(Swift)

I am new to Swift and I am getting response from mysql through PHP script in JSON format. But my JSON is in correct format :
["Result": <__NSArrayI 0x60000005bc60>(
<__NSArray0 0x608000000610>(
)
,
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
)
]
my code for serialisation is :
let url = URL(string: "my url")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "Id=\(Id)"
request.httpBody = body.data(using: .utf8)
// request.addValue("application/json", forHTTPHeaderField: "Content-type")
URLSession.shared.dataTask(with: request) { data, response, error in
if error == nil {
DispatchQueue.main.async(execute: {
do {
if let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Dictionary<String,Any>{
print(json)
Where am I going wrong?
POSTMAN output
{
"Result": [
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
]
}
Try it once.
let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
Swift 3.0
Try this code..
//declare parameter as a dictionary
let parameters = ["Id": Id"] as Dictionary<String, String>
//url
let url = URL(string: "http://test.com/api")!
//session object
let session = URLSession.shared
//URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
Alamofire
Try this code using Alamofire..
let parameters = [
"name": "user1"]
let url = "https://myurl.com/api"
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
failure(0,"Error")
}
}
Make sure you get the response as json. Some times get string as response. If you get string then convert that json string to json object.
Check it is a valid json object
let valid = JSONSerialization.isValidJSONObject(jsonOBJ) // jsonOBJ is the response from server
print(valid) // if true then it is a valid json object

Mysterious Network issues with posts. Wifi Works, Cell doesn't

I keep getting a timeout with sending post requests when my actual device is on 3G or 4G. However, when I'm on wifi, the post request is immediately received on the server side.
Here's my code that involves the post request. I'm getting a Optional("The request timed out."). I don't think the session length should be a problem since it times out after a long time and the data that is being sent is just a username with a password. Any thoughts?
I run a flask server, but I don't think it's relevant so I didn't include its code.
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
let url = NSURL(string: base_address + taglocation_address)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
print("starting task")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
self.statusLabel.text = error?.localizedDescription
print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
print("doing something")
if let responseJSON = json as? [String: String] {
print(responseJSON)
self.statusLabel.text = responseJSON["status"]
}
} catch let error as NSError {
self.statusLabel.text = error.localizedDescription
print(error)
}
}
task.resume()
}
In your NSMutableURLRequest object, try adding allowsCellularAccess property and set it to true. Refer to my code below.
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
let url = NSURL(string: base_address + taglocation_address)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.allowsCellularAccess=true //Add this line
print("starting task")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
self.statusLabel.text = error?.localizedDescription
print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
print("doing something")
if let responseJSON = json as? [String: String] {
print(responseJSON)
self.statusLabel.text = responseJSON["status"]
}
} catch let error as NSError {
self.statusLabel.text = error.localizedDescription
print(error)
}
}
task.resume()
}

POST w/ JSON Body - Swift3 - fragments?

I'm simply trying to send a JSON string via a Swift3 httprequest.
Tried using a Dictionary, and an escaped string ...
func getToken(successHandler: #escaping (Any) -> Void, errorHandler: #escaping (Any) -> Void) {
var request = URLRequest(url: URL(string: "http://my-api.domain.com/getToken")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do
{
// try with Dictionary
let bodyJson: [String: String] = [
"username": "theusername"
]
let bodyJsonData = try JSONSerialization.data(withJSONObject: bodyJson, options: [])
// try with escaped String
let jsonString = "{" +
"\"username\": \"theusername\"," +
"}"
let jsonStringData = jsonString.data(using: String.Encoding.utf8)
//request.httpBody = bodyJsonData
request.httpBody = jsonStringData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error)
errorHandler(error)
return
}
guard let data = data else {
print("Data is empty")
errorHandler("Data is empty")
return
}
var json: Any? = nil
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
DispatchQueue.main.asyncAfter(deadline: .now()) {
successHandler(json)
}
}
catch let error as NSError {
errorHandler(error)
}
}
task.resume()
}
catch
{
errorHandler(error)
}
}
I keep getting:
Handle Error: 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.}
I can't find how to try allowing fragments, all of the examples/tutorials are for Swift2.x :/
Unsure what to do!
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
// create post request
let endpoint: String = "https://yourAPI"
let session = URLSession.shared
let url = NSURL(string: endpoint)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = session.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
print(error?.localizedDescription)
return
}
}
task.resume()
} catch {
print("bad things happened")
}

Resources