1
我是Swift開發新手,現在我完全失去了。我製作了一個簡單的標籤並將其放置在Storyboard上。我的代碼根本沒有與它進行交互,但加載需要8-30秒,與默認情況下放置的其他UILabel不同。爲什麼是這樣?Swift:UILabel和UIImageView加載8-30秒
我對從URL獲取的圖像有同樣的問題。它立即下載圖像並將其分配給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
你的UI更新需要被分派到主線程 – dan
你怎麼在這?我將它包裝在DispatchQueue.main.async {}中,不起作用。 main.sync也不起作用。 – Holabola
'DispatchQueue.main.async {self.profilePicture.image = image; // UI更新代碼的其餘部分 }' –