我有一個函數,其中有2個if語句。代碼:秒如果語句在第一個語句在一個函數中完成之前被調用
func pictureFromFirebase(loginMethod: Int)
{
if loginMethod == 0 //FB
{
var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height":300, "width":300, "redirect":false], httpMethod: "GET")
let profilePicRef = storageRef.child((user?.uid)!+"/profile_pic.jpg")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
if (data != nil)
{
print("no need to download image from facebook")
self.profileImage.image = UIImage (data: data!)
}
}
}
if profileImage.image == nil
{
print("downloading image from facebook")
profilePic?.start(completionHandler: {(_ connection, _ result, _ error) -> Void in
if (error == nil)
{
if let dictionary = result as? [String:Any], let data = dictionary["data"] as? [String:Any],
let urlPic = data["url"] as? String {
if let imageData = NSData(contentsOf: NSURL(string: urlPic)! as URL)
{
let uploadTask = profilePicRef.put(imageData as Data, metadata: nil){
metadata, error in
if (error == nil)
{
let downloadUrl = metadata!.downloadURL
}
else
{
print("error in downloading image")
}
}
self.profileImage.image = UIImage(data: imageData as Data)
}
}
}
})
}
}
}
當這個功能被觸發它只有叫:
FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
print("called")
if let user = user {
if(activeUser != user){
let name = user.displayName
self.profileName.text = name
self.pictureFromFirebase(loginMethod: 0)
}
}
這是從調試,當我已經設定下載來自Facebook的圖像的圖像輸出正常不需要:
-called 從Facebook -downloading圖像-called 從Facebook -downloading形象 - 沒有需要從Facebook下載圖片- 沒有需要從Facebook
下載圖像這是從調試輸出,當我刪除整個第二if語句(如果profileImage.image ==無):
-called -called -no需要從Facebook下載圖片 -no需要從Facebook下載圖片
從我可以看到,除了函數被調用兩次,這也是錯誤的,第二個語句被調用之前執行第一個語句。由於第一條語句在設置profileImage之前需要一段時間,因此當第二條if語句正在檢查此值時,它爲零。我怎樣才能確保這不會再發生?謝謝。
請請請。詢問之前搜索。這已經被問及並且回答了數十萬次。 – matt