显示两个请求的指示符

时间:2016-06-20 07:51:41

标签: swift uiactivityindicatorview

我有两个请求。他们每个人都得到不同的数据。当所有两个请求都在请求时,我需要显示一个指示符。我怎么能这样做? 这是我的第一个要求:

func productList(tableView:UITableView,spinner:UIActivityIndicatorView,index1:Int,index2:Int,index3:Int){

    if product.count<=0{

        alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Default1",parameters: ["type1id":index1,"type2id":index2,"type3id":index3,"name":"","userid":1089])
            .responseJSON { response in
                guard response.result.error == nil else {
                    if let httpError = response.result.error {
                        switch(httpError.code){
                        case -1009:
                            let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK")
                            alert.show()
                            break
                        default:
                            let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK")
                            alert.show()
                            break
                        }
                    } else { //no errors
                        let statusCode = (response.response?.statusCode)!
                        print(statusCode)
                    }
                    spinner.stopAnimating()
                    UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                    return

                }

                if let value = response.result.value {
                    // handle the results as JSON, without a bunch of nested if loops
                    let product = JSON(value)
                    for (_,subJson):(String, JSON) in product {

                        let img:NSData
                        if let src=subJson["sphoto"].string{

                            if src.containsString("jpg"){
                                let range = src.startIndex.advancedBy(2)..<src.endIndex
                                let substring = src[range]
                                var urlString = "http://admin.unimax.kz/\(substring)"
                                urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
                                if let dataFromURL=NSData(contentsOfURL: NSURL(string: urlString)!){
                                    img=dataFromURL
                                }
                                else{
                                    img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                                }
                            }
                            else{
                                img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                            }
                        }
                        else{
                            img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                        }

                        //Do something you want
                        let id=subJson["id"].int!
                        let name=subJson["name"].string!
                        let price=subJson["price"].int!
                        let description=subJson["description"].rawString()
                        self.product.append(Product(id:id,title: name, img: UIImage(data: img), price: price,desc:description!))
                    }
                    spinner.stopAnimating()
                    UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                    tableView.reloadData()
                }
        }
    }
    else{
        spinner.stopAnimating()
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        tableView.reloadData()
    }
}

这是我的第二个请求:

func makeGetFav(userID:Int,completionHandler: (responseObject:JSON) -> ()) {
    alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Klientapi/?authid=\(userID)")
        .responseJSON {response in
            guard response.result.error == nil else {
                if let httpError = response.result.error {
                    switch(httpError.code){
                    case -1009:
                        let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK")
                        alert.show()
                        break
                    default:
                        let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK")
                        alert.show()
                        break
                    }
                } else { //no errors
                    let statusCode = (response.response?.statusCode)!
                    print(statusCode)
                }
                return
            }
            completionHandler(responseObject: JSON(response.result.value!))
    }
}

func getFavs(userID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){
    getFavRequets(userID){(responseObject) in
        if responseObject != nil{
            self.favs.removeAll()
            self.localDB.clearFav()
            for (_,subJson):(String, JSON) in responseObject {
                self.favs.append(FavModel(id: subJson["id"].int!, title: subJson["name"].string!, price: subJson["price"].int!))
            }
            spinner.stopAnimating()
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            tableView.reloadData()

        }
    }
}

我称之为:

UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    indicator.startAnimating()

    localDB.getUserInfo()
    getRequests.productList(tableView, spinner: indicator, index1: catalog1Index, index2: catalog2Index, index3: catalog3Index)
    if localDB.user.count>0{
        getRequests.getFavs(localDB.user[0].id, tableView: tableView, spinner: indicator)
    }
    localDB.checkCart(tableView, tabCtrl: tabBarController!)

5 个答案:

答案 0 :(得分:0)

一种非常快速的方法:

// global var

var isIndicatorActive : Bool = false


UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    indicator.startAnimating()
    self.isIndicatorActive = true

在您致电的每个alamoFireManager?.request之前的行中:

if isIndicatorActive == false {
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        indicator.startAnimating()
        self.isIndicatorActive = true
}

在每行spinner.stopAnimating()之后添加:

self.isIndicatorActive = false

答案 1 :(得分:0)

我建议您使用单个网络活动指示器并保留一个计数器,以跟踪应用程序中的网络活动。我知道我的答案更多是文本,但看看你的代码,你似乎可以实现以下内容。

0表示没有活动指示。

一旦新活动开始,递增计数器检查计数器是否大于0然后显示指示符。

活动任务完成后减少计数器。在减量时,检查计数器是否为0,然后将指标可见性设置为假。

PS:不要忘记在同步块中递增/递减。您可以使用objc_sync_enter(..)和objc_sync_exit(..)方法。

THX

答案 2 :(得分:0)

您可以使用单例来控制它,以根据运行请求的数量启动和停止它:

class NetworkActivityIndicator: NSObject {

    static let sharedInstance = NetworkActivityIndicator()

    private override init() {
    }

    var count = 0 {
        didSet {
            self.updateIndicator()
        }
    }

    private func updateIndicator() {
        if count > 0 {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        } else {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    }
}

您只需在请求前致电NetworkActivityIndicator.sharedInstance.count += 1,在获得回复时致电NetworkActivityIndicator.sharedInstance.count += 1

答案 3 :(得分:0)

最简单的方法是在类中添加两个变量来指示关联的请求是否完整,然后创建一个仅在两个变量都表明调用完成时才停止微调器的函数。

如果您想将该类用于多个ViewController,那么我建议添加一个struct-enum组合来组织指示当前正在进行哪些请求的变量。

例如

class GetRequests {

    var productsLoaded = false
    var favoritesLoaded = false

    func stopSpinnerIfNeeded(spinner: UIActivityIndicatorView) {
         if productsLoaded && favoritesLoaded {
             spinner.stopAnimating()
             spinner.hidden = true
         }
    }


    func productList(tableView:UITableView,spinner:UIActivityIndicatorView,index1:Int,index2:Int,index3:Int){

    defer {
        productsLoaded = true
        stopSpinnerIfNeeded(spinner)
    }

    if product.count<=0{

        alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Default1",parameters: ["type1id":index1,"type2id":index2,"type3id":index3,"name":"","userid":1089])
        .responseJSON { response in
            guard response.result.error == nil else {
                if let httpError = response.result.error {
                    switch(httpError.code){
                    case -1009:
                        let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK")
                        alert.show()
                        break
                    default:
                        let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK")
                        alert.show()
                        break
                    }
                } else { //no errors
                    let statusCode = (response.response?.statusCode)!
                    print(statusCode)
                }
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                return

            }

            if let value = response.result.value {
                // handle the results as JSON, without a bunch of nested if loops
                let product = JSON(value)
                for (_,subJson):(String, JSON) in product {

                    let img:NSData
                    if let src=subJson["sphoto"].string{

                        if src.containsString("jpg"){
                            let range = src.startIndex.advancedBy(2)..<src.endIndex
                            let substring = src[range]
                            var urlString = "http://admin.unimax.kz/\(substring)"
                            urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
                            if let dataFromURL=NSData(contentsOfURL: NSURL(string: urlString)!){
                                img=dataFromURL
                            }
                            else{
                                img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                            }
                        }
                        else{
                            img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                        }
                    }
                    else{
                        img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)!
                    }

                    //Do something you want
                    let id=subJson["id"].int!
                    let name=subJson["name"].string!
                    let price=subJson["price"].int!
                    let description=subJson["description"].rawString()
                    self.product.append(Product(id:id,title: name, img: UIImage(data: img), price: price,desc:description!))
                }
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                tableView.reloadData()
            }
        }
    }
    else{

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        tableView.reloadData()
    }
}

    func getFavs(userID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){
getFavRequets(userID){(responseObject) in
        if responseObject != nil{
            self.favs.removeAll()
            self.localDB.clearFav()
            for (_,subJson):(String, JSON) in responseObject {
                self.favs.append(FavModel(id: subJson["id"].int!, title: subJson["name"].string!, price: subJson["price"].int!))
            }

            favoritesLoaded = true
            stopSpinnerIfNeeded(spinner)
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            tableView.reloadData()

        }
    }
}

答案 4 :(得分:0)

感谢大家的帮助。我这样解决:

func makeReuest1(){
    if localDB.user.count>0{
        getRequests.getFavs(localDB.user[0].id)
    }
    makeRequest2()
}

func makeRequest2(){
    getRequests.productList(tableView, spinner: indicator, index1: catalog1Index, index2: catalog2Index, index3: catalog3Index)
}