HTTP response is blank - ios

I want to send dictionary data to server but server's POST response is showing blank.
func HitApi(callback: (NSDictionary) -> Void){
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ]
let jsonData:NSData?
do {
jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
}catch{
jsonData = nil
}
// create post request
let url = NSURL(string: "http://myserver.com")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Accept")
request.HTTPBody = jsonData
var dict = ["output":""]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in
if error != nil{
dict["output"] = "An error"
callback(dict)
}
do {
let data = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
dict["output"] = NSString(data: data!, encoding: NSUTF8StringEncoding)
callback(dict)
}catch{
dict["output"] = "error"
callback(dict)
}
}
task.resume()
}
If I use this code, then everything is going fine:
func HitApi(callback: (NSDictionary) -> Void){
let dataToSend:String = "1=First&2=Second"
let jsonData:NSData?
// create post request
let url = NSURL(string: "http://myserver.com")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Accept")
request.HTTPBody = dataToSend.dataUsingEncoding(NSUTF8StringEncoding)
var dict = ["output":""]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in
if error != nil{
dict["output"] = "An error"
callback(dict)
}
do {
let data = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
dict["output"] = NSString(data: data!, encoding: NSUTF8StringEncoding)
callback(dict)
}catch{
dict["output"] = "error"
callback(dict)
}
}
task.resume()
}
Now server is responding fine. But if i have big nested dictionary data then this method will be fail. What is problem in my first code?

Related

Making a url request session returns empty while postman returns data

I'm trying to make an API call here using a post method, however I keep getting
[[boringssl] boringssl_metrics_log_metric_block_invoke(144)]
and the data returned is an empty object {"finalResults":[]}.
Tested the API using postman and the data returns safely.
This is my code:
var dict = Dictionary<String, String>()
dict = [
"queryText": query,
"lat": "31.206865038834433",
"long": "29.965068562105422",
"pageToken": "",
]
let url:URL = URL(string: apiEndPointURLString)!
let session = URLSession.shared
var postData = NSData()
do{
postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
}catch {
print("error serializing.......\n\n\n\n")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("json/application", forHTTPHeaderField: "Accept")
request.httpBody = postData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "no data")
}
task.resume()

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

URLSession dataTask doesn't work

im new at swift and im trying to get response from a soap services, but the dataTask in my session never get in, always skip it. I already test te urls and the soap message but i don't have any lucky. Here is my code
func servisRun(){
let soapMessage = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/><soapenv:Body><tem:LogIn><tem:user>00002403</tem:user><tem:password>123456</tem:password></tem:LogIn></soapenv:Body></soapenv:Envelope>"
let msgLength = String(describing: soapMessage.characters.count)
let url = URL(string: "http://192.168.1.171/WcfSif.Services.Login.Login.svc")
var request = URLRequest(url: url!)
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
request.httpMethod = "POST"
request.httpBody = soapMessage.data(using: String.Encoding.utf8, allowLossyConversion: false)
URLSession.shared.dataTask(with: request) { (data, resp, error) in
guard error == nil && data != nil else{
print("connection error or data is nill")
return
}
if resp != nil {
self.mutableData?.length = 0;
}
let mutableData : Void = NSMutableData.initialize()
print(mutableData)
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.mutableData?.append(data!)
print(dataString!)
}
.resume()
let nsData = mutableData?.copy() as! NSData
let xmlParser = XMLParser(data: nsData as Data)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
}

sendSynchronousRequest is deprecated in ios 9 [duplicate]

This question already has an answer here:
Fixing NSURLConnection Deprecation from Swift 1.2 to 2.0
(1 answer)
Closed 7 years ago.
Xcode says that sendSynchronousRequest is now deprecated.
How should I replace it?
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 response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch _ as NSError {
urlData = nil
} catch {
fatalError()
}
This is a working example,
You should use NSURLSession, with Request.
func testPost(sender: UIButton) {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let d = "4"
let data = "x=4&y=\(d)"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
print("data =\(data)")
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
//if you response is json do the following
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
let arrayJSON = resultJSON as! NSArray
for value in arrayJSON{
let dicValue = value as! NSDictionary
for (key, value) in dicValue {
print("key = \(key)")
print("value = \(value)")
}
}
}catch _{
print("Received not-well-formatted JSON")
}
}
})
task.resume()
}
Notice it is not necessary to use the request. you can have a data task with URL, but I added the request because in your code, you have set some headers in the request.
Notice using the completionHandler which will be called when your server responses by http response.

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