raj kumar raj kumar - 14 days ago 5
Swift Question

How to display alert when api(json) has no data in swift 2.2

I am developing an app using Swift 2.2. In my app I am parsing (API) JSON data to table view when API has some data, I am able to parse it, but when API has no data, my app is terminating (crashing) so help me to display present view controller without terminating the app.

code in my view controller:

func jsonParsingFromURL () {

let url = NSURL(string: "https://www.something.com")


NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in

self.startParsing(data!)}

func startParsing(data: NSData){

let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

for var i = 0 ; i < (dict.valueForKey("driver_schedule") as! NSArray).count ; i++
{

arrDict.addObject((dict.valueForKey("driver_schedule") as! NSArray) .objectAtIndex(i))

TableView.reloadData()}

Answer

Create the following function which will allow you to display alert box:

func displayAlertMessage(msg: String){

    let alert=UIAlertController(title: "Alert", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
    let okAction=UIAlertAction(title: "Ok",style: UIAlertActionStyle.Default,handler: nil)
    alert.addAction(okAction)
    self.presentViewController(alert, animated: true, completion: nil)

}

and in your function jsonParsingFromURL check if response is nil,if its nil then call displayAlertMessage function to show alert box like this:

NSOperationQueue.mainQueue().addOperationWithBlock
    {
        self.displayAlertMessage("Your message");
    }

"NSOperationQueue.mainQueue().addOperationWithBlock" will allow you to call your function in the main ui thread,Since you are calling it inside another thread that is running asynchronously.

Comments