URLSession request no longer accepted by server - json

After reviewing and trying other questions and answers on StackOverflow I continue to have the following issue.
The app is meant to verify a user's username and password, then log them into the server on another screen provided the server authenticated that the user and password are valid.
The JSON response is meant to have a key Success and if it's a 1 then ok to log on else if 0 the user can not log on.
Worked fine with Swift 2 and I performed the recommended changes moving from Swift2 to Swift 3 and have no errors but have a strange response to the following code.
let body : String = ("username=\(tkUserName.text!)&password=\(tkPassword.text!)")
var request = NSMutableURLRequest()
request = NSMutableURLRequest(url: URL(string: "https://xxxxxxxxxxxx/LoginApp")!)
request.httpMethod = "POST"
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request as URLRequest)
{ (data, response, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if response == nil
{
//advise user no internet or other
}
else
{
var success : Int?
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
success = jsonResult!.object(forKey: "success") as? Int
}
catch let error as NSError
{
//action error
}
if success == 1
{
//capture all is good and go to other page
self.performSegue(withIdentifier: "unwindThenGoToTeamPage", sender: self)
}
else
{
//THIS IS WHERE IT DROPS INTO EACH TIME AS SUCCESS WAS "0"
}
}
}.resume()
Here is the server response
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 7/02/2017 10:19:31 AM
Event time (UTC): 6/02/2017 11:19:31 PM
Event ID: 1f9ff75ee64149b0994fa4a46a6ea03b
Event sequence: 5
Event occurrence: 1
Event detail code: 0
and
<NSHTTPURLResponse: 0x7b9ea440> { URL: https://xxxxxxxxxxxxx/teambeta/LoginApp } { status code: 200, headers {
"Cache-Control" = private;
"Content-Length" = 67;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 08 Feb 2017 03:48:09 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=ixxxxxxxxxxx; domain=xxxxx.com; path=/; HttpOnly, .ASPXAUTH=xxxxxxxxxxx; domain=xxxxx.com; expires=Fri, 10-Mar-2017 17:08:09 GMT; path=/; HttpOnly, TIsMobileDevice=True; path=/";
"X-AspNet-Version" = "4.0.30319";
"X-AspNetMvc-Version" = "5.2";
"X-Powered-By" = "ASP.NET";
} }
There is a lot more the server responded with but the issue seems to be with the URL Session I am creating. The JSON serialization is working fine but no Success key so I am not giving the server correct URL data.
And I checked that the server is still working fine for Swift2 as well as the Android and Windows versions so I know it's my code.

Try with the following code, this is working fine at my end. Pls check:
var request = URLRequest(url:url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(AUTENTICATION_KEY, forHTTPHeaderField: "AuthenticateKey")
request.httpBody = try! JSONSerialization.data(withJSONObject: json, options: [])
request.timeoutInterval = 30
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard data != nil else
{
print("no data found: \(error)")
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
completion(json)
}
catch let parseError
{
print(parseError)
// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON to load staff: '\(jsonStr)'")
}
})
task.resume()

Related

Posting user input JSON in Swift

I am trying to collect data from user and send it to an web service, however I get an error "invalid top-level type in JSON write" I am collecting the steps from the healthstore in another function and all the data is passed into the userhealthprofile variables correctly as it works printing them out. However something is wrong with my JSON code
Full error message is
2017-10-17 09:30:57.170950+0200 IphoneReader[347:40755] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(0x1d0b3b3d 0x1c33b067 0x1d0b3a85 0x1da763c1 0x9aa50 0x9bb60 0x2231a3b5 0x2231a349 0x22304979 0x22321f87 0x2286bf1b 0x22868833 0x22868423 0x22867849 0x223146f5 0x222e62bb 0x22a797f7 0x22a7419b 0x22a7457d 0x1d06ffdd 0x1d06fb05 0x1d06df51 0x1cfc11af 0x1cfc0fd1 0x1e76bb41 0x22349a53 0xa4d18 0x1c7ae4eb)
libc++abi.dylib: terminating with uncaught exception of type NSException
Code
#IBAction func submitAction(sender: AnyObject) {
userHealthProfile.name = nameLabel.text
print(userHealthProfile.name)
userHealthProfile.age = Int(ageLabel.text!)
print(userHealthProfile.age)
userHealthProfile.heightInMeters = Int(heightLabel.text!)
print(userHealthProfile.heightInMeters)
userHealthProfile.weightInKilograms = Int(weightLabel.text!)
print(userHealthProfile.weightInKilograms)
for element in stepy.step {
print(element)
}
userHealthProfile.totalStepsCount = stepy.step
print("pressing button")
//create the url with URL
let url = URL(string: "www.thisismylink.com/postName.php")!
//change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: userHealthProfile, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
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 {
//create 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()
}
This is what userprofile looks like, this is what I need to send as a jsonobject for my web service.
class UserHealthProfile {
var name: String?
var age: Int?
var totalStepsCount: Array<Any>!
var heightInMeters: Int?
var weightInKilograms: Int?
}
I think you should use Alamofire for calling web API..
Here is the sample code according to your requirements.
I hope this will help you...
func Submit(parametersToSend:NSDictionary)
{
Alamofire.request(.POST, "http://www.thisismylink.com/postName.php",parameters: parametersToSend as? [String : AnyObject], encoding: .URL).responseJSON
{
response in switch response.2
{
case .Success(let JSON):
print(JSON)
let response = JSON as! NSDictionary
print("My Web Api Response: \(response)")
break
case .Failure(let error):
print("Request failed with error: \(error)")
break
}
}
}
Function Calling in your #IBAction func submitAction(sender: AnyObject) like this
#IBAction func submitAction(sender: AnyObject) {
let steps = stepy.step
let name = nameLabel.text!
let age = Int(ageLabel.text!)
let height = Int(heightLabel.text!)
let weight = Int(weightLabel.text!)
let parameters = [
"name": name
"age": age
"totalStepsCount": steps
"heightInMeters": height
"weightInKilograms": weight
]
self.submit(parametersToSend:parameters)
}

iOS | server returns 415 status code (Swift 3)

I am sending login information to the server that I built using ASP.NET Core. I tested my server via PostMan and Fiddler and it returns a valid response.
Here is my post request:
var request = URLRequest(url: URL(string: "http://adincebic.com/auth/login")!)
request.httpMethod = "POST"
let postString = "email=cebic.ad#gmail.com&password=a"
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=\(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 = \(String(describing: responseString))")
}
task.resume()
I tried using dictionary like ["email":"myEmail","password":"myPass"] but it did not let me do it that way.
I also tried using Alamofire but again with no luck, the server always returns 415 error in the console.
To verify that my server works I created a UWP application to test it and it worked as expected.
Here is my server response in XCode:
statusCode should be 200, but is 415
response = Optional(<NSHTTPURLResponse: 0x6080002275a0> { URL: http://adincebic.com/auth/login } { status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 0;
Date = "Thu, 08 Jun 2017 12:16:12 GMT";
Server = "nginx/1.10.1 (Ubuntu)";
} })
responseString = Optional("")
I am assuming that it may be a problem with encoding or a problem with reading data.
I wrote this post requests as described in this answer: HTTP Request in Swift with POST method
Maybe you are missing the Content-Type header, like this:
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

How to send a POST request through Swift?

I have my controller like this -
def create
if (#user = User.find_by_email(params[:email])) && #user.valid_password?(params[:password])
render json: #user.as_json(only: [:email,:authentication_token]),status: :created
else
render json:('Unauthorized Access')
end
end
When I use Postman to make this request, I choose Body, and form data and adds in the email and password. And this WORKS
How to use swift to do the same? This is what I have tried
let url = URL(string: "http://localhost:3000/api/v1/user_serialized/")
let config = URLSessionConfiguration.default
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let bodyData = "email=Test#test.com&password=Test1234"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let session = URLSession(configuration: config)
let task = session.dataTask(with: url! as URL, completionHandler: {(data, response, error) in
let json = JSON(data:data!)
debugPrint(json)
})
task.resume()
I have made a Custom HTTP class where we can sent url, parameter and we will get Data from API. Below is the class.
import Foundation
//HTTP Methods
enum HttpMethod : String {
case GET
case POST
case DELETE
case PUT
}
class HttpClientApi: NSObject{
//TODO: remove app transport security arbitary constant from info.plist file once we get API's
var request : URLRequest?
var session : URLSession?
static func instance() -> HttpClientApi{
return HttpClientApi()
}
func makeAPICall(url: String,params: Dictionary<String, Any>?, method: HttpMethod, success:#escaping ( Data? ,HTTPURLResponse? , NSError? ) -> Void, failure: #escaping ( Data? ,HTTPURLResponse? , NSError? )-> Void) {
request = URLRequest(url: URL(string: url)!)
logging.print("URL = \(url)")
if let params = params {
let jsonData = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
request?.httpBody = jsonData//?.base64EncodedData()
//paramString.data(using: String.Encoding.utf8)
}
request?.httpMethod = method.rawValue
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30
session = URLSession(configuration: configuration)
//session?.configuration.timeoutIntervalForResource = 5
//session?.configuration.timeoutIntervalForRequest = 5
session?.dataTask(with: request! as URLRequest) { (data, response, error) -> Void in
if let data = data {
if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode {
success(data , response , error as? NSError)
} else {
failure(data , response as? HTTPURLResponse, error as? NSError)
}
}else {
failure(data , response as? HTTPURLResponse, error as? NSError)
}
}.resume()
}
}
Now you can refer below code to get how to make an API call.
var paramsDictionary = [String:Any]()
paramsDictionary["username"] = "BBB"
paramsDictionary["password"] = "refef"
HttpClientApi.instance().makeAPICall(url: "Your URL", params:paramsDictionary, method: .POST, success: { (data, response, error) in
// API call is Successfull
}, failure: { (data, response, error) in
// API call Failure
})
I think you should pass your request instead of the url to session.dataTask
here is how my code looks like:
private let url = URL(string: "http://example.com/")!
func httpPost(jsonData: Data) {
if !jsonData.isEmpty {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
NSLog("open tasks: \(openTasks)")
}
let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in
NSLog("\(response)")
})
task.resume()
}
}
Here is the Example of POST API for calling Login API with parameters "emailaddress" and "password" with userEmailID and Userpassword as two strings holding values for email and password respectively.
You can call this POST API anywhere in your view controller, as given below:
self.postLoginCall(url: "Your post method url") example: self.postLoginCall(url: "http://1.0.0.1/api/login.php")
func postLoginCall(url : String){
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
let postString = "emailaddress=\(userEmailID!)&password=\(Userpassword!)"
print(postString)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
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 { // check for fundamental networking error
print("error=\(error)")
return
}
do {
if let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject]{
print(responseJSON)
print(responseJSON["status"]!)
self.response1 = responseJSON["status"]! as! Int
print(self.response1)
//Check response from the sever
if self.response1 == 200
{
OperationQueue.main.addOperation {
//API call Successful and can perform other operatios
print("Login Successful")
}
}
else
{
OperationQueue.main.addOperation {
//API call failed and perform other operations
print("Login Failed")
}
}
}
}
catch {
print("Error -> \(error)")
}
}
task.resume()
}
Hello everyone I share below an example of a function to make a request in POST with SWIFT 5+.
This function allows you to send a POST request with an API entry point and parameters in the form of [[String: String]] and an Int to determine the output action.
For the output actions we call a function with Switch Case.
The operation is extremely simple. You have to put the two functions in one of your classes.
func MGSetRequestApi(endpoint: String, parameters: [[String: String]], MGSetAction: Int) -> String {
var setReturn: String!
let semaphore = DispatchSemaphore (value: 0)
var MGGetParam: String! = ""
for gate in parameters {
for (key, value) in gate {
let myParam = key + "=" + value + "&"
MGGetParam.append(contentsOf: myParam)
}
}
let postData = MGGetParam.data(using: .utf8)
var request = URLRequest(url: URL(string: endpoint)!,timeoutInterval: 10000)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
setReturn = String(data: data, encoding: .utf8)!
DispatchQueue.main.async {
self.MGRequestAction(MGGetIdRq: MGSetAction, MGGetData: setReturn)
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return setReturn
}
Then implement this function to manage the outputs
func MGRequestAction(MGGetIdRq: Int, MGGetData: String) {
switch MGGetIdRq {
case 1:
// Do something here
case 2:
// Do something else here
case 3:
// Do something else here again
default:
print("Set default action");
}
}
How to use this, you have two possibilities, the first one is to process what the function
MGSetRequestApi(endpoint: String, parameters: [[String: String]], MGSetAction: Int) -> String
returns (String) or to pass by the function
MGRequestAction(MGGetIdRq: Int, MGGetData: String)
which will call your Json parse function.
The MGRequestAction() function takes for parameter an Int for the choice of the action and the String of the return of the request
Now to use it do like this:
_ = MGSetRequestApi(endpoint: MY_END_POINT_API,
parameters: [["KEY_1": "VALUE 1"],
["KEY_2": "VALUE 2"],
["KEY_3": "VALUE 3"],
["KEY_4": "VALUE 4"]],
MGSetAction: 3)

How to change JSON POST request to handle HTTPS

Below is my login function. It's a JSON POST request and before, when the URL was http, it worked flawlessly. I attached a JSON filled with the username/password of the user. Today we added a SSL Certificate and after switching the URL to https, it produced this error:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
I'm not really sure what's going on. I typed that error into google and didn't get any where. I appreciate any help, thank you!
func login(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if response != nil {
if response.isKindOfClass(NSHTTPURLResponse) {
httpResponse = response as NSHTTPURLResponse
if let authorizationID = httpResponse.allHeaderFields["Authorization"] as String! {
Locksmith.saveData(["id":authorizationID], forUserAccount: currentUser, inService: "setUpAuthorizationId")
}
else {
println("Failed")
}
}
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr!)'")
postCompleted(succeeded: false, msg: "Error")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
if let status = parseJSON["status"] as? String {
if let extractData = parseJSON["data"] as? NSDictionary {
let extractUserId:Int = extractData["id"] as Int
userId = extractUserId
}
if status == "success" {
postCompleted(succeeded: true, msg: "Logged in.")
} else {
let failMessage = parseJSON["message"] as? String
postCompleted(succeeded: false, msg: failMessage!)
}
}
return
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
postCompleted(succeeded: false, msg: "Error")
}
}
})
task.resume()
}
Using This awesome article I was able to fix my problem. All I needed to do was add:
NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate
after my class name, and then add these two delegates:
func URLSession(session: NSURLSession,
didReceiveChallenge challenge:
NSURLAuthenticationChallenge,
completionHandler:
(NSURLSessionAuthChallengeDisposition,
NSURLCredential!) -> Void) {
completionHandler(
NSURLSessionAuthChallengeDisposition.UseCredential,
NSURLCredential(forTrust:
challenge.protectionSpace.serverTrust))
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
var newRequest : NSURLRequest? = request
println(newRequest?.description);
completionHandler(newRequest)
}
after that in my actual request I just needed to change:
var session = NSURLSession.sharedSession()
to:
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
hope this helps someone!!

How to POST JSON data using NSURLSession in swift

I am stuck with the below code. How do I set the param and in post method?
let params:[String:Any] = [
"email" : usr,
"userPwd" : pwdCode]
let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = params<what should do for Json parameter>
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if error {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
}
task.resume()
if I understand the question correctly
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
"email" : usr,
"userPwd" : pwdCode ]
let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result)
}
task.resume()
I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.
This is how you can set parameters and send a POST request, easy approach using Alamofire.
Swift 2.2
let URL = NSURL(string: "https://SOME_URL/web.send.json")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"
let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support#apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
do {
mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
// No-op
}
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(mutableURLRequest)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}