iosswiftswift2tableview

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

Solution

  • 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
        }
    }*/