简体   繁体   中英

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()
}

Please check this:

if let elim = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
{
    // Write your code here
    // Check whether it has value or not
    self.nullToNil(dict["driver_schedule"] as? String)!

    print("Valid")
}
else {
      print("Print here")
}

do {      
   var Arr: NSArray!
   Arr = dict.objectForKey("driver_schedule")! as! NSArray
   if(Arr.count > 0)
   {
      for x in 0... Arr.count - 1
      {
        let str = Arr.objectAtIndex(i)
        if(str.length > 0)
        {
          arrDict.addObject(Arr.objectAtIndex(i))
          TableView.reloadData()
        }
       }
    }
} catch _{}
/*override func nullToNil(value : String?) -> String?
{
    if value == nil
    {
        let str:String = ""
        return str
    }
    else
    {
        return value
    }
}*/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM