2016-07-24 21 views
-1

我在swift 2中的iOS版Firebase SDK存在問題。我試圖將圖片設置爲從Firebase存儲中下載的圖片。當我調用函數時,它返回零。我認爲它是因爲Firebase sdk提供的下載任務是異步的,所以當返回狀態意味着被稱爲必需的uid因爲任務尚未完成而未設置時。我如何解決這個問題,以便我得到正確的圖片?swift Firebase以異步方式返回任務

override func viewDidLoad() { 
    super.viewDidLoad() 
    imageView.image = downloadProfilePicFirebase() 
} 

的火力地堡下載功能:

func downloadProfilePicFirebase() -> UIImage{ 

    print("download called") 

    //local paths 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
    let documentDirectorPath:String = paths[0] 
    let imagesDirectoryPath = documentDirectorPath.stringByAppendingString("/profiles") 

    var uid = String() 


    if let user = FIRAuth.auth()?.currentUser { 
     let uid = user.uid 

     let storageRef = FIRStorage.storage().referenceForURL("gs://myid.appspot.com") 
     let profilePicRef = storageRef.child("/profile_pic.jpg") 

     let homeDir: NSURL = NSURL.fileURLWithPath(NSHomeDirectory()) 
     let fileURL: NSURL = homeDir.URLByAppendingPathComponent("Documents").URLByAppendingPathComponent("profiles").URLByAppendingPathComponent("profile_pic").URLByAppendingPathExtension("jpg") 

     // Download to the local filesystem 
     let downloadTask = profilePicRef.writeToFile(fileURL) { (URL, error) -> Void in 
      if (error != nil) { 
       print(error) 
      } else { 
       // svaed localy now put in ImageView 
      } 
     } 
    } 
    return UIImage(contentsOfFile: "\(imagesDirectoryPath)"+"/profile_pic_user_"+uid+".jpg")! 
} 
+0

請參閱本【答案】(http://stackoverflow.com/a/38439609/5654848)。 – Dershowitz123

+0

@ Dershowitz123是的,但返回的狀態意味着將在完成之前調用我想在這一點上保持功能 –

+0

也看到這個問題,並參考我的答案:http://stackoverflow.com/questions/38547875/how -to-運行obverveeventtype功能於主線程 –

回答

3

火力地堡是異步的,正如你所說,從而讓駕駛它你的應用程序中的數據流。

不要嘗試從Firebase塊返回數據 - 讓塊處理返回的數據,然後在塊中有效的數據移動到下一步。

有幾個選項:

一種選擇是從.writeToFile完成處理

override func viewDidLoad() { 
    super.viewDidLoad() 
    downloadPic() 
} 

func downloadPic { 
    let download = profilePicRef.writeToFile(localURL) { (URL, error) -> Void in 
     if (error != nil) { 
     // handle an error 
     } else { 
     imageView.image = UIImage(... 
     //then update your tableview, start a segue, or whatever the next step is 
     } 
    } 
} 

第二個選項是一個觀察者添加到節點和完成時,填充填充您的數據您的ImageView

override func viewDidLoad() { 
    super.viewDidLoad() 

    let download = storageRef.child('your_url').writeToFile(localFile) 

    let observer = download.observeStatus(.Success) { (snapshot) -> Void in 
    imageView.image = UIImage(... 
    //then update your tableview, start a segue, or whatever the next step is 
    } 
}