UIActivityIndi​​catorView 未显示

UIActivityIndicatorView not showing up

我正在尝试实现一个 UIActivityIndi​​catorView,它会在用户进行应用内购买时运行。由于某种原因,即使我已经制作了视图的子视图,UIActivityIndi​​catorView 也没有显示。

class RemoveAdsViewController: UIViewController {

@IBAction func btnAdRemoval(sender: UIButton) {
    let buyProgress = UIActivityIndicatorView(activityIndicatorStyle: .White)
    buyProgress.center = self.view.center
    self.view.addSubview(buyProgress)
    buyProgress.startAnimating()
    print(buyProgress)
    PFPurchase.buyProduct("", block: { (error:NSError?) -> Void in
        if error != nil{
            let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

            self.presentViewController(alert, animated: true, completion: nil)
        }
    })
    buyProgress.stopAnimating()
    buyProgress.removeFromSuperview()
}

PFRestore:

restoreProgress.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
       PFPurchase.restore()
       dispatch_async(dispatch_get_main_queue(), {
           restoreProgress.stopAnimating()
       })
 })

再看一看,问题就简单了。您过早地停止并删除了 activity 指标。您需要在完成块中停止并删除它。

@IBAction func btnAdRemoval(sender: UIButton) {
    let buyProgress = UIActivityIndicatorView(activityIndicatorStyle: .White)
    buyProgress.center = self.view.center
    self.view.addSubview(buyProgress)
    buyProgress.startAnimating()
    print(buyProgress)
    PFPurchase.buyProduct("", block: { (error:NSError?) -> Void in
        buyProgress.stopAnimating()
        buyProgress.removeFromSuperview()

        if error != nil{
            let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

            self.presentViewController(alert, animated: true, completion: nil)
        }
    })
}

您还需要确保完成块的内容正在主线程上完成。

问题是你这样做

buyProgress.startAnimating()

紧随其后

buyProgress.stopAnimating()

因为 PFPurchase.buyProduct 是一个异步调用,它会立即 return 并且您看不到 activity 指示器动画,因为它全部发生在一个 运行 循环周期中。

你需要移动

buyProgress.stopAnimating()

像这样在闭包里面

PFPurchase.buyProduct("", block: { (error:NSError?) -> Void in
            if error != nil{
                let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)
                buyProgress.stopAnimating()

                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                self.presentViewController(alert, animated: true, completion: nil)
            }
        })