我是Swift开发的新手,我现在完全迷失了。我制作了一个简单的标签并将其放在故事板上。我的代码根本没有与它交互,但加载需要8-30秒,与默认放置在那里的其他UILabel不同。为什么是这样?
对于从网址中提取的图片,我遇到了同样的问题。它立即下载图像并将其分配给UIImageView,但实际更新需要8-30秒,我不知道为什么。
这是我的控制器代码 FirstViewController.swift
import UIKit
class FirstViewController: UIViewController {
@IBOutlet var profilePicture: UIImageView!
var currentUser: User!
@IBOutlet var profileText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Declare currentUser variable
currentUser = User(email: "", first_name: "", last_name: "", department: "", admin: false, superadmin: false, thumb_url: "")
// Load timesheet structs
getTimesheetPages()
// Load user struct and wait for it to finish
getUserDetails() {
self.downloadProfilePic()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadProfilePic() {
let regURL = "http://localhost:3000"
let profilePicURL = URL(string: regURL + currentUser.thumb_url)!
let session = URLSession(configuration: .default)
// Define a download task
let downloadPicTask = session.dataTask(with: profilePicURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading profile picture: \(e)")
} else {
// No errors found.
if let res = response as? HTTPURLResponse {
print("Downloaded profile picture with response code \(res.statusCode)")
if let imageData = data {
print("Enters image load")
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
self.profilePicture.image = image
// Initialize profile picture properties
self.profilePicture.layer.borderWidth = 1.0
self.profilePicture.layer.masksToBounds = false
self.profilePicture.layer.borderColor = UIColor.white.cgColor
self.profilePicture.layer.cornerRadius = self.profilePicture.frame.size.width/2
self.profilePicture.clipsToBounds = true
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
// more functions
答案 0 :(得分:2)
正如Leo所说,我将整个函数调用包装在DispatchQueue.main.async { }
中,而不仅仅是UI更新调用。
将self.profilePicture.image = image
更改为
DispatchQueue.main.async {
self.profilePicture.image = image
// rest of UI update code
}
它完美无缺地运作