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

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]

Related

URLSession not returning anything

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()

iOS: Sending push notification to firebase services via url request

I'm building an test app to send push notifications here is my code:
static func sendRequestPush(){
let json: [String: Any] = ["to": "key",
"priority": "high",
"notification": ["body":"Hello1", "title":"Hello world","sound":"default"]]
let urlStr:String = "https://fcm.googleapis.com/fcm/send"
let url = URL(string:urlStr)
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
}
The problem is I don't get any response from googleapis neither the push notification. I get the push notification from dash board but not from my code.
Any of you knows what I'm doing wrong?
I'll really appreciate your help.
Try the below code, It works like charm :)
func sendRequestPush() {
// create the request
let url = URL(string: "https://fcm.googleapis.com/fcm/send")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("key=putYourLegacyServerKeyHere", forHTTPHeaderField: "authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = ["to": "putYourFCMToken",
"priority": "high",
"notification": ["body":"Hello1", "title":"Hello world","sound":"default"]] as [String : Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let dataTask = session.dataTask(with: request as URLRequest) { data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error!)
} else {
print(httpResponse!)
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let responseDictionary = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
print("The responseDictionary is: " + responseDictionary.description)
} catch {
print("error trying to convert data to JSON")
return
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
}
"putYourLegacyServerKeyHere" change this according to your key that you can get in FCM Console
"putYourFCMToken" change this with the fcm token you got in didReceiveRegistrationToken (FCM Delegate)

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

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()
}

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