Try block not working correctly - ios

I'm working on a app in which the api is called through NSURLSession. When the Api works correctly there is no problem but when no data is received due to any error then after Serialization it throws error but the else block for it is never called
let task = session.dataTaskWithRequest(request) { (let data, let response, let error) in
do {
guard let data:NSData = data , let response: NSURLResponse = response where error == nil else {
throw error!
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else{
print("Serialization failed") //This block never executes even if the Serialization Fails
throw JSONError.ConversionFailed
}
guard json.valueForKey("success") != nil else {
return
}
self.apidata = json
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
print(json.valueForKey("success")!)
}
catch let error as JSONError{
self.showalertview(error.rawValue)
print(error.rawValue)
} catch let error as NSError{
print(error.debugDescription)
}
}
task.resume()
What I'm doing wrong here???

Consider:
do {
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
// A
}
} catch {
// B
}
If NSJSONSerialization throws an error (i.e. if it wasn't really a JSON response or if the response was malformed), it will proceed directly to B and the guard statement doesn't come into play. The guard statement will only execute A if and only if (a) the NSJSONSerialization call, itself, didn't throw any errors (i.e. the JSON was well-formed); but (b) the cast to the the dictionary failed (e.g. the top level JSON object was an array instead of a dictionary). That's an extremely unlikely scenario (your server would have to accidentally return a well formed JSON response that was not a dictionary, e.g. a JSON array).
To accomplish what you want, you would use try? to make sure that NSJSONSerialization wouldn't throw any errors, itself:
do {
guard let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
// A
throw JSONError.ConversionFailed
}
} catch {
// B
}
By doing this, only if A performs a throw will B be called

Related

Repeat function with general command (without mentioning function name)

How do I repeat a swift function without naming that functions name?
Like if I have this function:
func repeatAtFail(){
let hasFailed = Bool.random()
if(hasFailed){
//repeat this function without calling function name
}
print("function succeed")
}
So I am looking for a general command to repeat a function. Just like "Return". But Return exits the function and I need one command that repeats it.
EDIT 11:08
This is the function I have
func loadRun(){
let request = get_request(postString: "function_name=get_run&userid=\(userid)&token=\(token!)")
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data else {
self.showErrorMessage()
//HERE I NEED TO REPEAT THE FUNCTION
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
self.showErrorMessage()
throw JSONError.ConversionFailed
}
if(checkErrors(json: json)){
self.showErrorMessage(message:json["error"] as! String)
return
}
self.data = json["payload"] as! [[String: Any]]
DispatchQueue.main.sync {
self.loadingBar.stopAnimating()
}
} catch let error as JSONError {
self.showErrorMessage()
print(error.rawValue)
} catch let error as NSError {
self.showErrorMessage()
print(error.debugDescription)
}
}.resume()
}
Occasionally it occurs that I get error -999 which is probably due to a failure of the SSL certificate on the domain. Till that issue is fixed I need a solution to reload the function so the users don't face any issues.

Swift 4 Ambiguous reference to member 'jsonObject(with:options:)'

Trying to setup a unit test which performs a network request and attempts to serialize the response. I'm currently getting the error: Ambiguous reference to member 'jsonObject(with:options:)'. Confused as to why this is happening as the unit test should know what JSONSerialization. is?
func testAccessKeys() {
let expected = expectation(description: "Run the Access request")
sut.request(.Access, data: nil) { finished, response in
if response != nil && finished == true {
guard let json = try? JSONSerialization.jsonObject(with: response!, options: .mutableContainers) as! [String:Any] else { return XCTFail("Access request was not a dictionary")}
XCTAssertNotNil(json?["id"])
expected.fulfill()
} else {
XCTFail("Access response was nil")
}
}
waitForExpectations(timeout: 3) { error in
if let error = error {
XCTFail("Access request failure: \(error)")
}
}
}
Make sure that response is of type Data or InputStream.
These are the only types that are accepted by this function as you can see in the documentation

Call can throw, but it is not marked with 'try' and the error is not handled Swift 4, SwiftyJSON [duplicate]

I am trying to use swiftyjson and I am getting an Error:
Call can throw, but it is marked with 'try' and the error is not
handled.
I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem
import Foundation
class lenderDetails
{
func loadLender()
{
let lenders = ""
let url = URL(string: lenders)!
let session = URLSession.shared.dataTask(with: url)
{
(data, response, error) in
guard let data = data else
{
print ("data was nil?")
return
}
let json = JSON(data: data)
print(json)
}
session.resume()
}
}
Thank you for all the help!
The SwiftyJSON initializer throws, the declaration is
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws
You have three options:
Use a do - catch block and handle the error (the recommended one).
do {
let json = try JSON(data: data)
print(json)
} catch {
print(error)
// or display a dialog
}
Ignore the error and optional bind the result (useful if the error does not matter).
if let json = try? JSON(data: data) {
print(json)
}
Force unwrap the result
let json = try! JSON(data: data)
print(json)
Use this option only if it's guaranteed that the attempt will never fail (not in this case!). Try! can be used for example in FileManager if a directory is one of the default directories the framework creates anyway.
For more information please read Swift Language Guide - Error Handling
You should wrap it into a do-catch block. In your case:
do {
let session = URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data else {
print ("data was nil?")
return
}
let json = JSON(data: data)
print(json)
}
} catch let error as NSError {
// error
}
Probably you need to implement do{} catch{} block. Inside do block you have to call throwable function with try.

NSJSONSerialization Error : Why am I not able to catch the error in try catch block? swift 3.0

I am calling REST API to get a response from the server and also testing for bad data type to caught in try catch block nut app still crashes with below error:
Could not cast value of type '__NSArrayM' (0x10575ee00) to 'NSDictionary' (0x10575f2d8).
let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error!)
return
}
do {
let responseObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,String>
print(responseObject)
} catch let jsonError {
print(jsonError)
}
}
dataTask.resume()
For this, I also found the solution that I should check data with JSON format first then use JSONSerialization.
if JSONSerialization.isValidJSONObject(data){
responseObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,String>
}
else {
print("Error")
}
I want to know that if type cast value error not caught by the try-catch block then what is a use of try-catch block in network call. I can simply check for the JSON format and the pass the response object.
What is a good programming practice?
NOTE : Error is not an issue I just don't want my should crash an app when data type changes form dictionary to array or other than specified type.
This is not about valid JSON, you are getting this crash because your JSON at root is Array not Dictionary and you are trying to cast the result of jsonObject(with:) to Dictionary that is the reason you are getting this crash also there is no need to specify mutableContainers with Swift.
do {
let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]]
print(responseObject)
} catch let jsonError {
print(jsonError)
}
Edit: If you don't know your JSON time then you can use if let like this way.
do {
let responseObject = try JSONSerialization.jsonObject(with: data, options: [])
if let responseArray = responseObject as? [[String:Any]] {
//Access array
}
else if let responseDictionary = responseObject as? [String:Any] {
//Access dictionary
}
print(responseObject)
} catch let jsonError {
print(jsonError)
}

Swift: Extra argument 'error' in call

I'm currently developing my first iOS app using Swift 2.0 and Xcode Beta 2. It reads an external JSON and generates a list in a table view with the data. However, I'm getting a strange little error that I can't seem to fix:
Extra argument 'error' in call
Here is a snippet of my code:
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil){
print(error!.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
if(err != nil){
print("JSON Error \(err!.localizedDescription)")
}
if let results: NSArray = jsonResult["results"] as? NSArray{
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
}
}
})
The error is thrown at this line:
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
Can someone please tell me what I'm doing wrong here?
With Swift 2, the signature for NSJSONSerialization has changed, to conform to the new error handling system.
Here's an example of how to use it:
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.
Here's the same example:
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
Things have changed in Swift 2, methods that accepted an error parameter were transformed into methods that throw that error instead of returning it via an inout parameter. By looking at the Apple documentation:
HANDLING ERRORS IN SWIFT:
In Swift, this method returns a nonoptional result and is marked with the throws keyword to indicate that it throws an error in cases of failure.
You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).
The shortest solution would be to use try? which returns nil if an error occurs:
let message = try? NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)
if let dict = message as? NSDictionary {
// ... process the data
}
If you're also interested into the error, you can use a do/catch:
do {
let message = try NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)
if let dict = message as? NSDictionary {
// ... process the data
}
} catch let error as NSError {
print("An error occurred: \(error)")
}
This has been changed in Swift 3.0.
do{
if let responseObj = try JSONSerialization.jsonObject(with: results, options: .allowFragments) as? NSDictionary{
if JSONSerialization.isValidJSONObject(responseObj){
//Do your stuff here
}
else{
//Handle error
}
}
else{
//Do your stuff here
}
}
catch let error as NSError {
print("An error occurred: \(error)") }

Resources