post parameter to sever using dictionary swift - ios

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

Related

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 avoid "Error Domain=NSCocoaErrorDomain Code=3840" in Swift?

I keep getting this particular error when trying to parse a JSON response in Swift:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Code:
let dict = [
"phone": phone,
"firstname": "\(String(describing: firstName))",
"lastname": "\(String(describing: lastName))"
]
as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
var request = URLRequest(url: URL(string: "\(config.baseURL)employee")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.timeoutInterval = 30.0
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
DispatchQueue.main.async {
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
guard let data_ = data else {
return
}
do {
let jsonObj = try JSONSerialization.jsonObject(with: data_, options: .mutableContainers) as? NSDictionary
guard let parseJSON = jsonObj else {
return
}
self.navigationItem.rightBarButtonItem = self.rightBarButton
let meta = parseJSON["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch let error as NSError {
print(error)
}
}
task.resume()
I have used similar codes in other parts of the project and everything checks out.
According to this Error, the response from your server is not a valid JSON
Can you use responseString instead of responseJSON like below
Alamofire.request(URL, method: requestMethod, parameters: params).responseString{ response in
print(response)
}
I was able to figure out what was wrong and I'm going to explain this here for future readers. Apparently, I was doing a GET request the wrong way, so when I intend to do a POST request, for some reason, it still sees it as a GET request and that was why I kept getting the response: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Below is my refactored code and it works without any hassle:
let dict = [
"phone": phone,
"firstname": firstName,
"lastname": lastName
] as [String : Any]
guard let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
return
}
guard let url = URL(string: "\(config.baseURL)employee") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData as Data
request.timeoutInterval = 10
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("JSON Response: \(response)")
}
if error != nil {
DispatchQueue.main.async {
self.navigationItem.rightBarButtonItem = self.rightBarButton
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
if let data = data {
do {
let parseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
let meta = parseJSON!["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch {
print(error)
}
}
}.resume()

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.

Swift JSON parsing username and password

I am trying to POST username & password as NSDictionary through JSON format. I am getting this following 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.}
My code is below:
#IBAction func loginAuthentication(_ sender: UIButton) {
let username : NSString = NameTextField.text! as NSString
let password : NSString = passwordTextField.text! as NSString
let parameters = [
"username": "\(username)",
"password": "\(password)"
]
print(parameters)
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
]
if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {
let request = NSMutableURLRequest(url: URL(string: "http://..")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
print(request.httpBody)
// let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if (error != nil) {
print("Error message \(error)")
} else {
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
{
let success = json["error"] as? Bool
print("Error from php\(success)")
let message = json["message"] as? String
// here you check your success code.
if (success == false)
{
print("Result1 \(message)")
self.performSegue(withIdentifier: "", sender: self)
}
else
{
self.dismiss(animated: true, completion: nil)
print("Result2 \(message)")
}
}
})
}
}
task.resume()
}
}
The problem looks to me like your string is not being serialized correctly. Instead of your current json serialization approach, simply convert a swift dictionary to data.
//Start with a dictionary
let body = [
"username": "bob",
"password": "admin"
]
//Serialize it.... you might want to put this in a do try catch block instead
let jsonBody = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
//Add it to the request
request.httpBody = jsonBody
//make the request, etc.
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response, error in

How to make rest api call with HTTP PUT method in swift

I have tried the below REST Api with PUT method.
Here is my code,
let url = NSURL(string: "http://sampleurl")
let request = NSMutableURLRequest(URL: url!)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "PUT"
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(), error: nil)
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
print("Parsed error: '\(error)'")
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Parsed JSON: '\(jsonStr)'")
}
}
dataTask.resume()
It is not working. Please help me to find out where it is wrong.
This is a working code, I send your dictionary as a JSON formatted string to the server, and in the server, I parse the request and build another JSON object that contains the same values as the request, and send them back to the app. In the app, I parse the response and print the results:
let session = NSURLSession.sharedSession()
let url = "http://localhost:8080/yourServerGoesHere/putMethodTest"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "PUT"
let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! NSHTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let deviceId = jsonData["deviceId"] as! String
let mobileDeviceId = jsonData["mobileDeviceId"] as! String
let deviceType = jsonData["deviceType"] as! String
print (" deviceId= \(deviceId), mobileDeviceId= \(mobileDeviceId), deviceType= \(deviceType)")
}catch _ {
print ("the response is not well JSON formatted")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
If you want to try, this is the Java web service code:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/putMethodTest")
#PUT
#Consumes(MediaType.TEXT_PLAIN)
public Response putMethodTest(String requestString) {
JSONObject requestJSON = new JSONObject(requestString);
String deviceId = requestJSON.getString("deviceId");
String mobileDeviceId = requestJSON.getString("mobileDeviceId");
String deviceType = requestJSON.getString("deviceType");
JSONObject response = new JSONObject();
response.put("deviceId", deviceId);
response.put("mobileDeviceId", mobileDeviceId);
response.put("deviceType", deviceType);
return Response.ok().entity(response.toString()).build();
}
Define the put function like this :
//
// Put request
//
static func put(path: String, accessToken: Bool, data: Dictionary<String, AnyObject>, finish: (accessTokenX:String, data: JSON) -> ()) {
apiRequest("PUT", path: path, accessToken: accessToken, contentType: nil, data: data) { (accessTokenX:String, data: AnyObject) in
dispatch_async(dispatch_get_main_queue(), {
finish(accessTokenX:accessTokenX, data: JSON(data))
})
}
}
An example of use :
//
// Update informations of the profile
//
static func accountUpdate(profile: [String: AnyObject], finish: (accessTokenX:String, data: JSON) -> ()) {
let dataProfile = ["profile": profile]
API.put("/users/profile", accessToken: true, data: dataProfile) { accessTokenX, data in finish(accessTokenX:accessTokenX, data: data)
}
}
Try this!!!
http://jamesonquave.com/blog/making-a-post-request-in-swift/
func data_request()
{
let url:NSURL = NSURL(string: url_to_request)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "data=Hello"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
}
task.resume()
}

Resources