首页 > 解决方案 > 在应用程序启动之前如何播放动画?

问题描述

我想为加载屏幕添加动画。我使用了网络服务。当我获取数据时,如何在等待获取数据时添加动画。(我使用 lottie pod )这是我的代码:

        animationViewLoading!.frame = self.view.bounds
        animationViewLoading!.backgroundColor = UIColor.darkGray
        animationViewLoading!.contentMode = .scaleAspectFit
        animationViewLoading!.loopMode = .loop
        animationViewLoading!.animationSpeed = 1.0
        self.view.addSubview(animationViewLoading!)
        animationViewLoading!.play()

此代码用于从 Web 服务获取数据

func getDataformWebService(){

let semaphore = DispatchSemaphore (value: 0)
var request = URLRequest(url: URL(string: "http://moodytest-env.eba-mmzgp9iv.eu-central-1.elasticbeanstalk.com/api/categories")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(APP_TOKEN)", forHTTPHeaderField: "Authorization")

request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  guard let data = data else {
    print(String(describing: error))
    return
  }
    do{
        // splash screen creat  and property
       
        
        timersplash = Timer.scheduledTimer(timeInterval: 1, target: ViewController.self, selector: #selector(ViewController.timerfuncloading), userInfo: nil, repeats: true)
        let categoriesDetails : CategoriesDetails = try JSONDecoder().decode(CategoriesDetails.self, from: data)
        category.append(contentsOf: categoriesDetails.categories)
   
        
    }catch{
        print(error.localizedDescription)
    }
  semaphore.signal()
}

task.resume()
semaphore.wait()

}

标签: iosswiftmobile

解决方案


您使用的是什么网络服务?如果您询问 api 调用,一种方法是使用 dispatchGroup。

例如:

func getData(){

   let dispatchGroup = DispatchGroup()

   dispatchGroup.enter()
   FetchData().fetchData(url: url) { (data, error) in
           print(data) //load or print data
           dispatchGroup.leave()
   }


    dispatchGroup.notify(queue: .main) {
         animationViewLoading.stop()   //Stop the animation after data has 
                                         finished printing or loading
    }

}

如果您需要进一步的帮助,请告诉我!


推荐阅读