Https Post Request Response - ios

private func makeLoginRestCall(email:String, password:String){
guard let url = URL(string: "http://-----------/PassengerLogin.php") else {
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
let emailString : String = "email="
let parameters = emailString + email+",password=" + password
request.httpBody = parameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with:request) {
(data,response,error) in
if let response = response {
print(response)
}else{
print("No response")
}
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
print(json ?? "No data found")
}catch{
print(error)
}
}else {
print("No data found")
}
}.resume()}
When I send this request from simulator I always get invalid email response.
But When I send this request from postman I get all user details .
Please help new here
Thank you in advance.

Related

How to Pass Key Value Parameter in JSON POST method in Swift?

This is API http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/
its parameter: "contactsList" : ["5987606147", "6179987671", "5082508888"]
its header: ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
In my code if i put breakpoint then filtertaggedUser() is calling but i am unable to go inside completionHandler the access is not going inside dataTask
Access going to else part why? the api is working.
i am trying to pass parameter key value in URL string like below
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
is this correct approch?
code for above API:
func filtertaggedUser() {
print("inside filter taggedusers")
let headers = ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
// access not coming here
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
print("filter taggedusers inside")
do {
print("filter taggedusers inside do")
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
print("filter taggedusers \(jsonObject)")
} catch { print(error.localizedDescription) }
} else { Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self) }
})
dataTask.resume()
}
OUTPUT:
POSTMAN OUTPUT
POSTMAN Body
why response is not coming, where i did mistake, please help me with the code.
We can call the Post request API like below,
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
print(data.map { String($0) }.joined(separator: "&"))
return data.map { String($0) }.joined(separator: "&")
}
func callPostApi(){
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
request.setValue("personal", forHTTPHeaderField: "userType")
let parameters = getPostString(params: ["contactsList":["8908908900"]])
request.httpBody = parameters.data(using: .utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
print(httpResponse!.statusCode)
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
Output :
{"8908908900":{"userId":"9609cc826b0d472faf9967370c095c21","userName":"Satish Madhavarapu","profilePic":null,"oniTaag":true,"tagged":false,"userType":"personal"}}

Sending Http Post request returns 500 status code in IoS

I am trying to send Receipt data of NSData type(converted to string) and several other parameters of type as String in Http Post request.
func receiptValidation(productId:String)
{
let SUBSCRIPTION_SECRET = My_SecretKey
let defaults = UserDefaults.standard
let receiptPath = Bundle.main.appStoreReceiptURL?.path
if FileManager.default.fileExists(atPath: receiptPath!){
var receiptData:NSData?
do{
receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
}
catch{
print("ERROR: " + error.localizedDescription)
}
let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
// let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)
let requestDictionary = ["receipt-data":receiptString!,"password":SUBSCRIPTION_SECRET]
guard JSONSerialization.isValidJSONObject(requestDictionary) else { print("requestDictionary is not valid JSON"); return }
do {
let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)
let requestDataString = NSString(data: requestData, encoding: String.Encoding.utf8.rawValue)
//https://<apiProxyServer>:<apiProxyServerPort>/api/validate-receipt-data
let URLForApplication:String = String(format:"%#/api/validate-receipt-data",opcodeDetails["apiProxyBaseUrl"]!) // this works but as noted above it's best to use your own trusted server
let url:URL! = URL.init(string: URLForApplication)
var request = URLRequest.init(url: url)
request.httpMethod = "POST"
let configure = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier!)
var postString:[String:Any]=[
"receiptData": requestDataString
"deviceType":"IOS",
"subscriberId":encodeString(normalString: defaults.array(forKey: "userDetails")?.first as! String),
"password":encodeString(normalString: defaults.array(forKey: "userDetails")?.last as! String),
"productId":encodeString(normalString: productId),
"code":opcodeDetails["opCode"]!
]
do {
let receiptData = try JSONSerialization.data(withJSONObject: postString)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = receiptData
} catch let error {
print(error.localizedDescription)
}
let session = URLSession(configuration:configure,
delegate:applicationDelegate.application,
delegateQueue:OperationQueue.main)
session1 = session
let connection = session1?.dataTask(with: request)
connection?.resume()
} catch let error as NSError {
print("json serialization failed with error: \(error)")
}
}
}
Where encodeString() is a defined method
func encodeString(normalString:String) -> String {
let allowedCharacters = CharacterSet.letters
let encodedString:String!=normalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
return encodedString
}
There were no problem on server side.But I could not get success response instead What I am getting is {"status":"failure","statusCode":500,"message":"Resource url not found!"}.What mistake am i doing with this code?.Anyone please help me.Thanks in advance.
Try appending '/' at the end of URL.
Eg:
google.com/api/post and google.com/api/post/ are different and trailing slash sometimes gives 500 error, in case of Django-Backend it does.

Json response "GET" request: "No session Found" - Swift

I want to make a "GET" request to apache web server to retrieve some data. Before making the above request, I log in making a "POST" request, the web server opens a new session and I get the json response:
gotten json response dictionary is
["user": {
email = "asd#asd.it";
password = "<null>";\\ for security reason it doesn't return the password
sessionID = 6C61269BB7BB40682E96AD80FF8F1CB7;
}]
So far it's all correct. But then when I try to make the "GET" request to retrive the user's data, I get this response:
gotten json response dictionary is
["message": {
errorCode = F01;
errorDetails = "No session is found in the server, either you have not set the JSESSIONID cookie or the session does not exists";
message = "No session Found";
}]
The code for the "POST" request is:
let urlComp = NSURLComponents(string: "http://localhost:8080/mnemosyne/auth")!
let postDict: [String:Any] = ["email": "asd#asd.it", "password" : "password"]
var items = [URLQueryItem]()
for (key,value) in postDict {
items.append(URLQueryItem(name: key, value: value as? String))
}
urlComp.queryItems = items
var urlRequestAuth = URLRequest(url: urlComp.url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000)
urlRequestAuth.httpMethod = "POST"
let postData = try? JSONSerialization.data(withJSONObject: postDict, options: [])
urlRequestAuth.httpBody = postData
let taskAuth = URLSession.shared.dataTask(with: urlRequestAuth) { (data, response, error) in
guard error == nil else {
print(error as Any)
return
}
guard let content = data else {
print("No data")
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}
print("gotten json response dictionary is \n \(json)")
}
taskAuth.resume()
This is the code for "GET":
let url = URL(string: "http://localhost:8080/mnemosyne/rest/task")
var request = URLRequest(url: url!)
let taskTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {
print ("error: \(error!)")
return
}
guard let content = data else {
print("No data")
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}
print("gotten json response dictionary is \n \(json)")
}
taskTask.resume()
What's the problem? How can I pass in the request the session Id that I want to use?
I think you need send sessionID in your GET request.
I would at first try some util like Postman or RESTed free apps, to test request and understand how to send correct POST request.
Depending on server implementation - you could send session ID as a part of url, in POST body or in POST header.

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)

How to send array by POST method to server?

I am trying to send array as parameter to server but server is not receiving. Server have to receive two arrays that I am sending. But in server they are not appear ?? I dont know is it my mistake or mistake in the server ??
My array name is testAns and testQuest and I have to send it to parameters: answer and quest.
my Code:
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(testAns)&quest=\(testQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}
i don't know how to encode that array on your server side.
but temporary you can try this way and check your database.
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer[0]=131&answer[1]=123&quest[0]=123&quest[1]=233"
You can use the Alamofire that is very popular at this time that is advanced version of AFNetworking
Also, I am sharing the method that will help you to hit API, You have to pass only the dictionary object in this method and this will give you the response in two blocks and you can use them as per requirements.
1: unReachable()
2: handler(responseDict)
//MARK: *********** HIT POST SERVICE IN JSON FORM***********
func hitPostServiceJsonForm(_ params:Dictionary<String,Any>,unReachable:(() -> Void),handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
if networkReachable() == false {
unReachable()
}
let BASE_URL = "http://mydoamain"
var request = URLRequest(url: URL(string: BASE_URL)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
print(BASE_URL)
Alamofire.request(request).responseJSON { response in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict)
}
else{
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil)
print(error)
break
}
}
}
func networkReachable() -> Bool {
return (NetworkReachabilityManager()?.isReachable)!
}
convert the your array to json string then try to send it to server
func post_array(){
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
var tempAns : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testAns, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempAns = string! as NSString
}catch let error as NSError{
print(error)
}
var tempQuest : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testQuest, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempQuest = string! as NSString
}catch let error as NSError{
print(error)
}
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(tempAns)&quest=\(tempQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}

Resources