我正在做天气应用程序,一切都很好,直到我将CAGradientLayer
转换添加到UIView
。它仍然有效,但过渡时间过长,大约10-15秒。我正在使用Apixu API来应对天气。有一点需要注意的是音频是完美的播放,马上。我检查了持续时间,动画没有错:
import UIKit
import AVFoundation
class ViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var cityLbl: UILabel!
@IBOutlet weak var conditionLbl: UILabel!
@IBOutlet weak var degreeLbl: UILabel!
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var gradientView: UIView!
let gradientLayer = CAGradientLayer()
let gradientLayer2 = CAGradientLayer()
let gradientLayer3 = CAGradientLayer()
var degree: Int!
var condition: String!
var imgURL: String!
var city: String!
var exists: Bool = true
var audioPlayer1 = AVAudioPlayer()
var audioPlayer2 = AVAudioPlayer()
var audioPlayer3 = AVAudioPlayer()
var audioPlayerSunny = AVAudioPlayer()
var audioPlayerSnow = AVAudioPlayer()
var audioPlayerThunder = AVAudioPlayer()
// Audio part.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
gradientLayer.frame = gradientView.bounds
gradientLayer.colors = [UIColor.blue.cgColor, UIColor.black.cgColor]
gradientView.layer.insertSublayer(gradientLayer, at: 0)
//gradient color view
gradientLayer2.colors = [UIColor.red.cgColor, UIColor.purple.cgColor]
//gradient color view 2
gradientLayer3.colors = [UIColor.orange.cgColor, UIColor.green.cgColor]
//gradient color view 3
searchBar.delegate = self
// Audio Code starts.
do {
audioPlayer1 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "ambiance", ofType: "mp3")!))
audioPlayer1.prepareToPlay()
audioPlayer2 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "guitar", ofType: "mp3")!))
audioPlayer2.prepareToPlay()
audioPlayer3 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "rain", ofType: "mp3")!))
audioPlayer3.prepareToPlay()
audioPlayerSunny = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sunny", ofType: "mp3")!))
audioPlayerSunny.prepareToPlay()
audioPlayerSnow = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "snow", ofType: "mp3")!))
audioPlayerSnow.prepareToPlay()
audioPlayerThunder = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "thunder", ofType: "mp3")!))
audioPlayerThunder.prepareToPlay()
}
catch {
print(error)
} // Audio Code ends.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
let urlRequest = URLRequest(url: URL(string: "http://api.apixu.com/v1/current.json?key=494942fa74444eabb6973325170510&q=\(searchBar.text!.replacingOccurrences(of: " ", with: "%20"))")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let current = json["current"] as? [String : AnyObject] {
if let temp = current["temp_c"] as? Float {
self.degree = Int(temp.rounded())
}
if let condition = current["condition"] as? [String : AnyObject] {
self.condition = condition["text"] as! String
let icon = condition["icon"] as! String
self.imgURL = "http:\(icon)"
}
}
if let location = json["location"] as? [String : AnyObject] {
self.city = location["name"] as! String
}
if let _ = json["error"] {
self.exists = false
}
if self.condition == "Sunny" || self.condition == "Clear" {
self.audioPlayerSunny.currentTime = 0
self.audioPlayerSunny.play()
self.audioPlayer1.stop()
self.audioPlayer3.stop()
self.audioPlayer2.stop()
self.audioPlayerSnow.stop()
self.audioPlayerThunder.stop()
// Audio Code.
let colorChangeAnimation = CABasicAnimation(keyPath: "colors")
colorChangeAnimation.duration = 1.0
colorChangeAnimation.toValue = self.gradientLayer3.colors
colorChangeAnimation.fillMode = kCAFillModeForwards
colorChangeAnimation.isRemovedOnCompletion = false
self.gradientLayer.add(colorChangeAnimation, forKey: "colorChange")
//effects
} else if self.condition.lowercased().range(of:"cloudy") != nil || self.condition.lowercased().range(of:"overcast") != nil {
self.audioPlayer1.currentTime = 0
self.audioPlayer1.play()
self.audioPlayer2.stop()
self.audioPlayer3.stop()
self.audioPlayerSnow.stop()
self.audioPlayerSunny.stop()
self.audioPlayerThunder.stop()
// Audio Code.
let colorChangeAnimation = CABasicAnimation(keyPath: "colors")
colorChangeAnimation.duration = 1.0
colorChangeAnimation.toValue = self.gradientLayer2.colors
colorChangeAnimation.fillMode = kCAFillModeForwards
colorChangeAnimation.isRemovedOnCompletion = false
self.gradientLayer.add(colorChangeAnimation, forKey: "colorChange")
//effects
} else if self.condition.lowercased().range(of:"snow") != nil || self.condition.lowercased().range(of:"snowy") != nil || self.condition.lowercased().range(of:"sleet") != nil
{
self.audioPlayerSnow.currentTime = 0
self.audioPlayerSnow.play()
self.audioPlayer2.stop()
self.audioPlayer3.stop()
self.audioPlayer1.stop()
self.audioPlayerSunny.stop()
self.audioPlayerThunder.stop()
// Audio Code.
} else if self.condition.lowercased().range(of:"rain") != nil || self.condition.lowercased().range(of:"rainy") != nil || self.condition.lowercased().range(of:"drizzle") != nil
{
self.audioPlayer3.currentTime = 0
self.audioPlayer3.play()
self.audioPlayer2.stop()
self.audioPlayer1.stop()
self.audioPlayerSnow.stop()
self.audioPlayerSunny.stop()
self.audioPlayerThunder.stop()
// Audio Code.
} else if self.condition.lowercased().range(of:"thunder") != nil || self.condition.lowercased().range(of:"thundery") != nil {
self.audioPlayerThunder.currentTime = 0
self.audioPlayerThunder.play()
self.audioPlayer2.stop()
self.audioPlayer3.stop()
self.audioPlayerSnow.stop()
self.audioPlayerSunny.stop()
self.audioPlayer1.stop()
// Audio Code.
} else {
self.audioPlayer2.currentTime = 0
self.audioPlayer2.play()
self.audioPlayer1.stop()
self.audioPlayer3.stop()
self.audioPlayerSnow.stop()
self.audioPlayerSunny.stop()
self.audioPlayerThunder.stop()
// Audio Code.
}
DispatchQueue.main.async {
if self.exists{
self.degreeLbl.isHidden = false
self.conditionLbl.isHidden = false
self.imgView.isHidden = false
self.degreeLbl.text = "\(self.degree.description)°"
self.cityLbl.text = self.city
self.conditionLbl.text = self.condition
self.imgView.downloadImage(from: self.imgURL!)
}
else {
self.degreeLbl.isHidden = true
self.conditionLbl.isHidden = true
self.imgView.isHidden = true
self.cityLbl.text = "No matching city found"
self.exists = true
}
}
} catch let jsonError {
print(jsonError.localizedDescription)
}
}
}
task.resume()
}
}
extension UIImageView {
func downloadImage(from url: String) {
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error == nil {
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}
}
task.resume()
}
}