URLSession not returning anything - ios

This is the code :
let url = URL(string: requestUrl)
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if bodyDict != nil && type(of: bodyDict) != NSNull.self {
var jsonString: String? = nil
if let anError = try? JSONSerialization.data(withJSONObject: bodyDict ?? [String: Any](), options: .prettyPrinted) {
jsonString = String(data: anError, encoding: .utf8)
}
if jsonString != nil {
print("bodyDict : \(bodyDict)")
request.httpBody = try? JSONSerialization.data(withJSONObject: bodyDict ?? [String: Any]())
}
}
let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
if error != nil {
print("APIClient failed to get InApp Messages: \(error?.localizedDescription ?? "" )")
} else {
var responseString = String(data: data!, encoding: .utf8)
var responseDict: [AnyHashable : Any]? = nil
if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [String : Any]
print("sessionId responseDict : \(responseDict)")
}
if responseDict == nil {
responseString = "{\"error\":\"\(responseString ?? "")\"}"
print("sessionId error : \(responseString)")
if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [AnyHashable : Any]
}
}
}
})
dataTask.resume()
But dataTask never returns anything, not even error. Same request on postman works fine. bodyDict :
["latitude": "76.69", "event_name": "nitishtest", "cart_id": "60",
"platform": "1", "auth_token":
"1aae7a2afa86b0f0ede377ca29c5a503b837054f", "session_id": "12",
"push_device_id": "522", "longitude": "0", "campaign_id": "1967",
"brand": "nike"]

Alright, so I found the fix. For iOS 11, I had to set waitsForConnectivity for URLSession. I was testing on iOS 11.x
So the code is as follows for URLSession :
let configuration = URLSessionConfiguration.default
configuration.httpCookieStorage = nil
configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
if #available(iOS 11.0, *) {
configuration.waitsForConnectivity = false
}
let session = URLSession(configuration: configuration)

You should not call datatask.resume() separately.
call .resume() function after dataTask closing bracket.
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
}.resume()

Related

How to add post api request in parameters while parsing in swift

This is my api request:
{
"billDetails": {
"billerId":"EPDCLOB00AN232",
"customerParams":[{"name":"Service Number","value":"116515M025033"}]
}
}
here is code:
func billerFetchService(){
let parameters = ["billDetails": {
"billerId" : "EPDCLOB00ANP01",
"customerParams" : [{"name":"Service Number","value":"116515M025007621"}]
}
] as [String : Any]
let url = URL(string: "https://app.com/Fetch/fetch")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if response != nil {
// print(response)
}
if let data = data {
do{
var json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("fetching json \(json)")
}catch{
print("error")
}
}
}).resume()
}
if i add like this in parameters error
Consecutive statements on a line must be separated by ';'
Insert ';'
Expected expression
Where i did mistake, please help me in code
You need
let parameters = ["billDetails": [
"billerId" : "EPDCLOB00ANP01",
"customerParams" : [["name":"Service Number","value":"116515M025007621"]]]]
Please make your parameter as this
let parameters = ["billDetails":
[
"billerId": "EPDCLOB00ANP01",
"customerParams" : ["name":"Service Number","value":"116515M025007621"]
]
] as [String : Any]

Swift - JSON data wont display in UITableview

I am trying to retrieve data from a server. I can display my data in the console.
I'm trying to display it in a UITableview but nothing happens.
I tried to create a local JSON file and I am able to display it, but when coming from the server it wont work.
let newUrl = URL(string: urlGetNotifications)
let configuration = URLSessionConfiguration.default
var session = URLSession.shared
var request = URLRequest(url: newUrl!)
session = URLSession(configuration: configuration)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(authkeyFCM, forHTTPHeaderField: "auth-key")
request.setValue(tokenFCM.string(forKey: "tokenFCM"), forHTTPHeaderField: "token")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
DispatchQueue.main.async {
guard let j = newUrl
else{
print("data not found")
return
}
guard let d = try? Data(contentsOf: j)
else { print("failed")
return
}
guard let rootJSON = try? JSONSerialization.jsonObject(with: d, options: [])
else{ print("failedh")
return
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
if let JSON = rootJSON as? [String: Any] {
print("data: \(dataString)")
guard let jsonArray = JSON["data"] as? [[String: Any]] else {
return
}
print(jsonArray)
let name = jsonArray[0]["type"] as? String
print(name ?? "NA")
print(jsonArray.last!["created_at"] as? String as Any)
self.notificationList = jsonArray.compactMap{return NotificationData($0)}
self.tableView.reloadData()
}
}
}
})
task.resume()
create a variable for the URL and create struct contain the all param
in the main add variable of type the struck then start fetch the data
var users: [User]() = []
func fetchUsers(using url: String){
let url = URL(string: url)!
let _ = URLSession.shared.dataTask(with: url){ (data,response,error)
in
guard let data = data else {return}
do{
let userFetch = try JSONDecoder().decode([Post].self, from: data) // decode * ( Codable )
self.users = userFetch
self.load(with: userFetch)
self.userCollection = userFetch
DispatchQueue.main.async {
self.collectionView.reloadData()
}
} catch{
print("error loading data cause: \(error)")
}
}.resume()
}
I figured it out
This one works
let newUrl = URL(string: urlGetNotifications)
let configuration = URLSessionConfiguration.default
var session = URLSession.shared
var request = URLRequest(url: newUrl!)
session = URLSession(configuration: configuration)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(authkeyFCM, forHTTPHeaderField: "auth-key")
request.setValue(tokenFCM.string(forKey: "tokenFCM"), forHTTPHeaderField: "token")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
DispatchQueue.main.async {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
//self.showSpinner(onView: self.view)
print("The Response is : ",json)
if let data = data, let dataString = String(data: data, encoding: .utf8) {
if let JSON = json as? [String: Any] {
print("dumaan ba dito")
print("data: \(dataString)")
guard let jsonArray = JSON["data"] as? [[String: Any]] else {
return
}
print(jsonArray)
let name = jsonArray[0]["type"] as? String
print(name ?? "NA")
print(jsonArray.last!["created_at"] as? String as Any)
self.notificationList = jsonArray.compactMap{return NotificationData($0)}
self.tableView.reloadData()
}
}
} catch {
print("JSON error: \(error.localizedDescription)")
}
} // end
})
task.resume()

Unable to post parameters in post request ios swift

I'm trying to send these parameters as a post request to the URL but the parameters are not getting sent. I don't know whether is URLSession configuration issue. Can anyone check and solve the issue?
import UIKit
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var str = String(data: jsonData!, encoding: .utf8)
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
Check with this:
func post method(){
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"]
let parameters = ["set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as! Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
}
guard let httpresponse = response as? HTTPURLResponse,
(200...299).contains(httpresponse.statusCode) else {
print ("server error")
return
}
if let mimeType = response?.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("got data: \(dataString)")
}
}
})
dataTask.resume()
}
I used an online service called RequestBin to inspect your request and data seem to be sent correctly. I only did minor modifications as already mentioned in the comment.
This was the resulting code:
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try! JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://requestbin.fullcontact.com/***")! // Was "using"
var request = URLRequest(url: url)
request.httpMethod = "POST" // Was "Post"
request.httpBody = jsonData // Was utf8 string representation
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
You can check inspected result using this service. You simply create a new URL and use it in your request. After you have successfully sent the request all you do is reload the page to inspect your request.
Note that these are "http" requests so you need to allow arbitrary loads.
You may set your request like following and change content type according to your need
import UIKit
let json: [String: Any]? = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let parameters = json
{
self.makeParamterString(request: request, parameterDic: parameters)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
static func makeParamterString(request:NSMutableURLRequest, parameterDic:[String:AnyObject])
{
let _ = NSCharacterSet(charactersIn:"=\"#%/<>?#\\^`{|}").inverted
var dataString = String()
for (key, value) in parameterDic {
dataString = (dataString as String) + ("&\(key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)=\(value)")
}
dataString = dataString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
request.httpBody = dataString.data(using: String.Encoding.utf8)
}

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.

post parameter to sever using dictionary swift

I am trying to send data to the server using a dictionary but unfortunately the data is not saving to the database (fields were found to be blank) and I am getting the below response:
Optional(["status": true, "msg": successfull])
And also tried to show UIActivityIndicator to user until he got a response but couldn't find a way.
Code attempted:
let dict = [ "key_one": self.tf1.text!,"key_two":self.tf2.text!]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
// create post request
let url = NSURL(string: "myAPIUrl.php?")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Response -> \(result)")
} catch {
print("Inside Error Section -> \(error)")
}
}
task.resume()
} catch {
print(error)
}
// write this in one fucantion
let Username:NSString = EmailTextField.text! as NSString
let password:NSString = PasswordTextField.text! as NSString
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
]
let parameters = [
"username": "\(Username)",
"password": "\(password)"
]
if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {
var request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
{
let success = json["status"] as? Int
let message = json["message"] as? String
// here you check your success code.
if (success == 1)
{
print(message)
let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
present(vc, animated: true)
}
else
{
// print(message)
}
}
})
}
}
task.resume()
}

Resources