Data posting server gets error in swift 3? - ios

Here i got a token number from api like as shown here "210" and it is saving using userdefaults but when i tried to retrieve data from the userdefaults then it is returning "\"210\"" like this why it is adding slashes and quotes can anyone help me how to resolve this ?
here is the code for posting key
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.CustomerToken!)", forHTTPHeaderField: "Authorization")
print(self.CustomerToken!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
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: .utf8)
print("responseString = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(responseString!)
self.customerCartIdNumber = responseString!
self.customerCartIdNumber = responseString!
UserDefaults.standard.set(self.customerCartIdNumber, forKey: "CustomerLoginNumber")
print(self.customerCartIdNumber!)
print(responseString!)
here is the code for getting key
let customerId = UserDefaults.standard.string(forKey: "CustomerLoginNumber")
self.customerCartId = customerId!
print(customerId!)
here is the code for posting
func customerAddToCartItemsDownloadJsonWithURl(cartApi: String){
let url = URL(string: cartApi)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
let cartNumber = customerCartId?.replacingOccurrences(of: "\\", with: "")
let parameters : [String: Any] = ["cartItem":
[
"quote_id": "\(customerCartId!)",
"sku": "\(itemCode!)",
"qty":"1"
]
]
print(customerCartId)
print(parameters)
print(cartNumber)
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("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
}

Related

I try post string request but its not working my code

ı try to send string request but its not work
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = "{\"Language\": \"tr\",\"ProcessType\": 1,\"Username\": \"\(self.mailTextField.text ?? "")\",\"Password\": \"\(self.passwordTextField.text ?? "")\"}"
print(parameters)
let enUrlParams = try! parameters.aesEncrypt(key: LoginConstants.xApiKey, iv: LoginConstants.IV)
print(enUrlParams)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
request.httpBody = enUrlParams.data(using: .utf8)
Output:
{"Language": "tr","ProcessType": 1,"Username": "","Password": ""}
l+Au1MhqAlHr+wDR9UmdjN4IL5XHVnwMJx3rHF/P1MT+aO5Q5YF25f5OJRwDVzXEWu47ocqMxcUqw1onYBya9VCEvqjNQ0FpNCxtPp9fh+Y=
Optional(108 bytes)
statusCode should be 200, but is 500
response = Optional(<NSHTTPURLResponse: 0x600000e36e00> { URL: "my url" } { Status Code: 500, Headers {
Date = (
"Wed, 14 Sep 2022 11:54:35 GMT"
);
Server = (
"Microsoft-IIS/10.0"
);
"Transfer-Encoding" = (
Identity
);
"X-Powered-By" = (
"ASP.NET"
);
} })
responseString = Optional("")
If you are getting 500 as HTTP Response Code, then you need to check with the API Team, as 500 is Server Not Available.
If, Status Code lies in 4xx, then you need to bother about code, For 5xx you Server /API is not responding to your request.
I solved problem let stringRequest = ""(enUrlParams)"" this part solved my problem
let url = URL(string: MemberUrl)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = "{\"Language\": \"tr\",\"ProcessType\": 1,\"Username\": \"\(self.mailTextField.text ?? "")\",\"Password\": \"\(self.passwordTextField.text ?? "")\"}"
print(parameters)
let enUrlParams = try! parameters.aesEncrypt(key: LoginConstants.xApiKey, iv: LoginConstants.IV)
print(enUrlParams)
let stringRequest = "\"\(enUrlParams)\""
print(stringRequest)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = stringRequest.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
if let responseString = String(data: data, encoding: .utf8) {
print("responseString = \(String(describing: responseString))")
self.userDC = responseString ?? ""
self.userDC = try! self.aesDecrypt(key: LoginConstants.xApiKey, iv: LoginConstants.IV)
print(self.userDC)
self.login()
}
})
task.resume()

Swift 4 - When sending POST request to localhost, my URLRequest sends the JSON data with the dictionary as a key

Seems like a simple error, but I cannot resolve it for some reason:
let parameters = ["user_id":usernameTF.text!, "password": passwordTF.text!]
let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
print(parameters)
print(jsonData!)
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.httpMethod = "POST"
debugTV.text = "\(parameters["user_id"]!)"+"\(parameters["password"]!)"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options:[])
// pass dictionary to nsdata object and set it as request body
print(request.httpBody!)
} catch let error {
print(error.localizedDescription)
}
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
return
}
guard let data = data else {
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
let responseString = String(data: data, encoding: .utf8)
print(responseString!)
}
when see the NodeJS debug window, my request body is
req.body = { '[password: "test", user_id: "test"]':'' }
how can I convert the request data into a JSON object?

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.

HTTP Send Request Parameter in Swift

i want to send request with username and password for getting authentication key from server, here is my code, i don't know how send to parameter with request, please help me for solve it.
let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate"
func recentProfileURL(parameter : [String:String]?) -> NSURL {
let component = NSURLComponents(string: urlString)!
var queryItem = [NSURLQueryItem]()
if let param = parameter {
for (key,value) in param {
let item = NSURLQueryItem(name: key, value: value)
queryItem.append(item)
}
}
component.queryItems = queryItem
return component.URL!
}
func fetchCode(completion completion: (ProfileResult) -> Void){
let request = NSURLRequest(URL: recentProfileURL(["UserName": self.userNameParam]))
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) in
let result = self.processUserProfileRequest(data: data, error: error)
completion(result)
})
task.resume()
}
I'm trying send username and password for getting authentication code from server how can send array of parameter instead of one parameter?
Try this I hope it would be helpful for you!!
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
try this code
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
This should work for you:
var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")`
}

swift ios mobile app login submit

I'm trying to program an iOS application for this website of our university: https://uniworx.ifi.lmu.de/
I failed with the login. I have managed it to send a http submit for the login form, but I always get the same site back as response. I want to get the site you normally see after logging in. What am I doing wrong?
Here is the code of my function:
func newTest()
{
let request = NSMutableURLRequest(url: NSURL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")! as URL)
request.httpMethod = "POST"
let postString = "username=myusername&password=mypassword"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard error == nil && data != nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString)")
}
task.resume()
}
I've changed my real username and password in the code -of course-.
Try this I hope it would be helpful for you!!
In Swift 2+
let request = NSMutableURLRequest(URL: NSURL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
In Swift 3 You can
var request = URLRequest(url: URL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")!)
request.httpMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(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 = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()

Resources