Swift 2.0 POST Body null - ios

Using a packet analyzer, I'm getting that my HTTP body is null. Is there any reason why my params aren't getting sent in the POST request?
let request = NSMutableURLRequest(URL: NSURL(string:"SERVERURL")!)
request.HTTPMethod = "POST"
do {
let params = ["returnInt":"5"] as Dictionary<String,String>
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch {
//Do nothing
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("\(responseString)")
}
task!.resume()

As I saw with println() in the Playground, the request.HTTPBody is not nil. Also, my analyzer shows not nil either:

Related

swift - how to get JSON response from server

I'm sending this data to a server and I would like it to respond. Tried this code but it doesn't work.
let parameters = [ "imie" : (imie), "nazwisko" : (nazwisko), "telefon" : (telefon), "adres" : (adres), "miasto" : (miasto), "kod" : (kod), /*"powiat" : (powiat), "wojewodztwo" : (wojewodztwo),*/ "opis" : (selectedvalue) ]
let url = URL(string: "http://www.hetman.pl/post1.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setBodyContent(parameters)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if error != nil{
return
}
do{
let t = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print(t as? String)
} catch{
print("Error 43 -> \(error)")
}
}
Request is correct and server is processing data properly, but response gives me this error:
Error 43 -> Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}
So the question is, how do I get the data back from server?
Please check if response from this url is JSON only. You might be getting XML or string response.
Try below line if you are getting String response :
let stringResponse = String(data: data!, encoding: String.Encoding.utf8) as String!
Try below line if you are getting XML response :
let xmlDictionary = try XMLSerialization.xmlObject(with: data!) as? [String: Any]
Why there is to content type?
// code 3840, data.length = 1 byte, so empty and no error
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Remove first content-type header field and try with only:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

INPUT_VALIDATION_ERROR in BetFair Login API / iOS

I am getting INPUT_VALIDATION_ERROR while logging into betfair api. I am following the docs, but it was of no use with this particular error code.
I'd appreciate if anyone could guide me in the right direction.
Here is my swift code
let request = NSMutableURLRequest(URL: NSURL(string: "https://identitysso.betfair.com/api/login")!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("MY_APP_KEY", forHTTPHeaderField: "X-Application")
let postString = "username=MY_USER_NAME&password=MY_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
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
I think you need to set header in http for Content-Type as
application/x-www-form-urlencoded
Three parameters in Http header:
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setHeader("X-Application", <apiKey>);

How i can POST (send the file to server) a video in swift 2.0?

How i can POST (send the file to server) a video in swift 2.0? I have the url of the file. How i can GET the video in server side.
//url from server
let url = NSURL(string: "http://myurl/uploadvideo.php")
//video url
let pathString = blabla.relativePath
Usually i post with JSON like this:
let parameters = ["Nombre":"\(nombre.text)", "Correo":"\(correo.text)", "Edad":"\(edad.text)", "Mensaje":"\(mensaje.text)"] as Dictionary<String, String>
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setBodyContent(parameters)
//create dataTask using the session object to send data to the server
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let strData =
NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
print("account data")
if(error != nil) {
print(error!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
else {
}
})
task.resume()
Thanks and sorry for my bad english :)

HTTP Request with Body using PATCH in Swift

I'm trying to send a Patch request with a serialized JSON Body.
For some reason the server is not able to receive the body properly. I have a feeling that there seems to be a problem with the PATCH method in combination with the http request body.
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
var URL = B2MFetcher.urlForBooking(event.unique, bookingID: booking.unique)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "PATCH"
// Headers
println(token)
request.addValue(token, forHTTPHeaderField: "Authorization")
request.addValue("gzip, identity", forHTTPHeaderField: "Accept-Encoding")
// JSON Body
let bodyObject = [
"op": "cancel"
]
var jsonError: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(bodyObject, options: nil, error: &jsonError)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
completion(data: data, response:response , error: error)
})
task.resume()
You could try to add a Content-Type header to the request:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or use one of the other JSON Content-Type formats described here.
I tested it with an ExpressJS server and without the Content-Type header the server got an empty body, but with a Content-Type header it worked well.
in swift 3/4 :
let request = NSMutableURLRequest(url: NSURL(string: "http://XXX/xx/xxx/xx")! as URL)
request.httpMethod = "PATCH"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do{
let json: [String: Any] = ["status": "test"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
request.httpBody = jsonData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
} catch {
print("ERROR")
}
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
completion(false)
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
completion(true)
return
}
task.resume()
Simple Way to use patch without using HTTPBody
If you want to just use patch, you just need to change the value of the name of a specific user then it will be like:
let myurl = URL(string: "https://gorest.co.in/public-api/users/"+"\(id)?"+"name=abc")!
var request = URLRequest(url:myurl)
request.addValue("Bearer yourAuthorizationToken",forHTTPHeaderField:"Authorization")
request.httpMethod = "PATCH"
let dataTask = URLSession.shared.dataTask(with: request)
dataTask.resume()
Note: here "id" will be userId

Swift: Save responseString ID to String

Sending this code with HTTP POST returns an ID, but I'm so far unable to extract the ID from responseString and save it as it's own String in my app.
I'm looking into using Alamofire, perhaps that'll make things easier but I was hoping to be able to do it using just Swift code. Any help is appreciated.
var parseError: NSError?
let date = NSDate()
let timeStamp = date.timeIntervalSince1970
var request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let params = ["name":fullName.text, "number":phoneNumber.text, "email":emailAddress.text, "timeStarted":timeStamp] as Dictionary<String, AnyObject>
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil)
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
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
let idFromServer = responseString?.valueForKeyPath("id") as String!
println(idFromServer)
var dateID = idFromServer
newUser.setValue(dateID, forKey: "dateID")

Resources