I've got a struct, which contains a static variable called userProfileImage, this struct is in a view controller called UserProfilePage.swift, here is the code:
struct UserProfile {
static let userProfileImage = UIImageView(image: #imageLiteral(resourceName: "profilePicture"))
}
class UserProfilePage: UIViewController {
// Some code that sets the userProfileImage to another image
}
The following code is in another swift file that has a struct called Downloads:
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
When profilePicURL
is not empty, some code gets executed, but when it is empty (equal to ""
), the code inside the else block gets executed. The problem is that the profile picture doesn't change, it just executes the print statement inside the else block. Does anyone know what's wrong with my code?
First of all, you have to change your userProfileImage . This Should be a var instead of **static let.
You can use if let statement with an async call in your code. Please try the following code.
let profilePictureString = "http://SOME URl STRING.."
if let profilePicURL = URL(string: profilePictureString){
// Plcae Your Network Code Here.
} else {
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
}
}
You can call the setNeedsDisplay()
for update the imageview
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
UserProfile.userProfileImage.setNeedsDisplay()
}
use image literal
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = imageLiteral(resourceName: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.