iosswift

How to use a custom activity indicator view while using API call in my project


I am new on Stack Overflow , learning Swift and now I am making a project of API call.

I want to use a custom activity indicator view until the data fetched from API . So please help me to short out the issue in my code . I have imported JTMaterialSpinner library in my project.

This is the spinner (the custom activity indicator view) I want to show:

enter image description here

This is my code:

var spinerrview : JTMaterialSpinner = JTMaterialSpinner(frame: CGRectZero) 

override func viewDidLoad()
{
     super.viewDidLoad()
     spinerrview.circleLayer.strokeColor = UIColor.greenColor().CGColor spinerrview.circleLayer.lineWidth=2.0 
     spinerrview.frame.size.height=25.0 
     spinerrview.frame.size.width=25.0
     spinerrview.circleLayer 
     spinerrview.isAnimating=true
     spinerrview.backgroundColor=UIColor.greenColor() 
     spinerrview.beginRefreshing()
     getdata() 
     spinerrview.endRefreshing() 
}

hare i give whole code

import UIKit
import Alamofire
import SwiftyJSON
import JTMaterialSpinner

class ViewController: UIViewController ,UITextViewDelegate,UITableViewDataSource{
    var arrRes = [[String:AnyObject]]()
    var spinerrview : JTMaterialSpinner = JTMaterialSpinner(frame: CGRectZero)
    @IBOutlet weak var table: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        spinerrview.circleLayer.strokeColor = UIColor.redColor().CGColor
        spinerrview.circleLayer.lineWidth=3.0
        spinerrview.circleLayer
        spinerrview.isAnimating=true
        spinerrview.frame.size.height=25.0
        spinerrview.frame.size.width = 25.0
        spinerrview.center=table.center
        spinerrview.beginRefreshing()
        getdata(NSURL(string: "http:api.androidhive.info/contacts/")!, completionHandler: { (success) -> Void in
            // When your API call was terminated, control flow goes here.
            self.spinerrview.endRefreshing()
            if success {
                print("success")
            } else {
                print("fail")
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    typealias CompletionHandler = (success:Bool) -> Void
    func getdata(url: NSURL,completionHandler: CompletionHandler) {
        Alamofire.request(.GET, url).validate().responseJSON { response in
            var flag = false // true if call is succeed,false otherwise
            switch response.result {
            case .Success(let data):
                flag=true
                let swiftyJsonVar = JSON(data)
                if let resData = swiftyJsonVar["contacts"].arrayObject {
                    self.arrRes = resData as! [[String:AnyObject]]
                }
                self.table.reloadData()
            case .Failure(let error):
                flag=false
                print("Request failed with error: \(error)")
            }
            completionHandler(success: flag )
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell  = tableView.dequeueReusableCellWithIdentifier("jsonCell")!as! TableViewCell
        var dict = arrRes[indexPath.row]
        cell.name.text = dict["name"] as? String
        return cell
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrRes.count
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        performSegueWithIdentifier("gotoview", sender: self)
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if(segue.identifier == "gotoview") {
          let indexPat = self.table.indexPathForSelectedRow!
            let vc = segue.destinationViewController as! secondViewController
          vc.adde = "add   "+(arrRes[indexPat.row]["address"] as? String)!
             vc.mail = "mail   "+(arrRes[indexPat.row]["email"] as? String)!
             vc.iid = "id   "+(arrRes[indexPat.row]["id"] as? String)!
             vc.nam = (arrRes[indexPat.row]["name"] as? String)!
             vc.ph = "phone   "+(arrRes[indexPat.row]["phone"]!["mobile"]as? String)!
            }
    }
} 

Solution

  • Your issue is in these three lines:

    spinerrview.beginRefreshing()
    getdata() 
    spinerrview.endRefreshing()
    

    The spinner start in main thread, getdata() was launched and it probably make some work in a background thread so you don't know when it's finish, and spinner ended right after getdata was called. It's like in real life when you press the light button ON/OFF immediatly .

    To avoid this kind of issue, you could create a completionHandler for your getdata() function (API call):

    typealias CompletionHandler = (success:Bool) -> Void
    func getdata(url: NSURL,completionHandler: CompletionHandler) {
        // API call code.
        let flag = true // true if call is succeed,false otherwise
        completionHandler(success: flag)
    }
    

    Usage:

    spinerrview.beginRefreshing()
    getdata(NSURL(string: "http://...")!, { (success) -> Void in
        // When your API call was terminated, control flow goes here.
        spinerrview.endRefreshing()
        if success { 
            // API call success
        } else {
            // API call fail
        }
    })
    

    Update: (after your new edit to add getdata())

    typealias CompletionHandler = (success:Bool) -> Void
    
    func getdata(url: NSURL,completionHandler: CompletionHandler) {
        Alamofire.request(.GET, url).validate().responseJSON { response in
            var flag = false // true if call is succeed,false otherwise
            switch response.result {
            case .Success(let data):
               flag=true
               let swiftyJsonVar = JSON(data)
               if let resData = swiftyJsonVar["contacts"].arrayObject {
                  self.arrRes = resData as! [[String:AnyObject]]
               }
               self.table.reloadData()
            case .Failure(let error):
               flag=false
               print("Request failed with error: \(error)")
            }
            completionHandler(success: flag )
        }
    }