Can we get the HttpStatus Code error description in swift? - swift2

I am using Uber Api in my app. There is problem which occurs when I try to book a ride.I get a httpStatus 400 error. As per their documentation, this could arise due to a variety of factors.
How can I know through status code(Always"400") as to which description of given types causes it?.
My code now:
if let httpstatuscode = response as? NSHTTPURLResponse
{
if (error != nil)
{
print("Error : \(error?.localizedDescription)")
}
else if httpstatuscode.statusCode != 202 && httpstatuscode.statusCode != 409
{
print("Status Code\(httpstatuscode.statusCode)")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
CommonViewController.alertViewUI("Alert", message: "Internal Server Error!")
})
}
else if httpstatuscode.statusCode == 409
{
// self.getUberRideLive()
print("Status Code\(httpstatuscode.statusCode)")
CommonViewController.alertViewUI("Alert", message: "You are already on a ride!")
}

You can use the localizedString(forStatusCode:) method from HTTPURLResponse class
This is valid if you want to obtain descriptions for HTTP erros, if you want description from UBER errors you should look at JSON response from UBER operation.
Then, your code should looks like...
let message: String = HTTPURLResponse.localizedString(forStatusCode: httpstatuscode.statusCode)

Related

URL Sessions returning server not found even though URL is valid - Swift4

I am trying to use URLSession to do a API Request. The request/link is the following https://api.nanopool.org/v1/zec/user/t1KcroGeTYz6Tn4hsgwnuiUzw65xgAAaknc
When I put it into safari it loads. When I try preform the request in Xcode 9 with Swift4, I get an error that the server was not found.
Here is the entire error.
The top to lines are just from a print function, the rest is the error.
Here is the code I used:
let api = "https://api.nanopool.org/v1/zec/user/"
let urlString = api+addr
print(urlString)
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
print(data)
}.resume()
What is the issue with it that it causing it to return that the server cannot be found even though its a valid URL/Request?

Handling cocoa errors from (NS)URLSession in Swift 3

How to handle errors from cocoa frameworks in Swift 3 now that NSError is gone?
Swift 3 improved NSError Bridging - https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md
What I do not understand from that document is how to use the improved error bridging.
Let's say, I have the following code, written in Swift 2.3, where I'm trying to find out what the actual error is:
NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
guard let error = error { else return }
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
print("cancelled.")
} else {
print("error occured: \(error)")
}
}
The corresponding Swift 3 method provides plain Error in its completion handler according to the documentation:
func dataTask(with url: URL, completionHandler: #escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
How do I migrate the mentioned code to Swift 3? I guess casting to NSError is not the correct answer.
Error is a protocol which includes also a potential NSError.
I guess casting to NSError is the right answer.
Practically just optional bind to NSError
URLSession.shared.dataTask(with: url) { data, response, error in
guard let nserror = error as? NSError else { return }
if nserror.domain == NSURLErrorDomain && nserror.code == NSURLErrorCancelled {
print("cancelled.")
} else {
print("error occured: \(nserror)")
}
}
If you have more different errors use a switch statement and pattern matching.

Xcode Swift macOS, Terminal App not doing NSURLSession

Trying to poll the content of a website, no matter if JSON or REST API, I cannot seem to make it work. The same code works for iOS App, but will not get the content when being used within a Swift macOS Terminal application. What's the main reason?
The project does not have an Info.plist file.
Here's a code example that works within an iOS application, but not within the macOS Terminal application. I call the function with a simple jsonParser(), which initiates the NSURLSession and prints the JSON when it's arrived.
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let urlPath = "https://api.coindesk.com/v1/bpi/currentprice.json"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
I was able to solve my problem by adding
dispatch_main()
at the end of my main program code. Listed above was the function to request the web data. Thanks to Martin and Eric for pointing it out.

How to send some count of POST/GET requests simultaneously?

I'm learning swift, trying to send 2 and more requests not one by one, but simultaneously. Is it possible with NSURLSession?
NSURLSession is asynchronous which means it is sent on a different thread and can be run multiple at once.
This link explains and gives an example on how to handle the response back on the main thread etc:
https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started
func sendRequest() {
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var dataTask: NSURLSessionDataTask?
let url = NSURL(string: "http://www.url.com")
dataTask = defaultSession.dataTaskWithURL(url!) {
data, response, error in
dispatch_async(dispatch_get_main_queue()) {
//Handle response
if let error = error {
//Error - handle 'error'
print(error.localizedDescription)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
//Success - handle 'data'
}
}
}
}
dataTask?.resume()
}
Hope this helps

FBSDKGraphRequest cannot post image and text anymore (no more text)

I'm posting to a group user wall, (image and text). It have worked from a long time, and stop working recently(now, image are posted, but no text :( ). Any idea if there was a new way or rules? (no error reported)
[params setObject:sContent forKey:#"message"];
[params setObject:yourImageData forKey:#"picture"];
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"xxxxxxxxxxxxxxx/photos"
parameters: params
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
Following is the working code for me(In Swift):
let params = ["message": "Test message", "sourceImage" : UIImagePNGRepresentation(UIImage(named: "test.jpg")!)!]
FBSDKGraphRequest(graphPath: "me/photos", parameters: params, HTTPMethod: "POST").startWithCompletionHandler({ (connection, result, error) -> Void in
guard let response = result else {
print("No response received")
if let errorInfo = error {
print("errorInfo: \(errorInfo)")
}
return }
print(response)
})
Check 'Publishing' section at the link for more.
Let me know if you have any difficulties to convert it to Objective-C.

Resources