swift Firebase在异步任务

时间:2016-07-24 09:38:11

标签: ios swift xcode asynchronous firebase

我在swift 2中遇到了适用于iOS的Firebase SDK的问题。我试图将图片设置为从Firebase存储下载的图片。当我调用该函数时,它返回nil。我认为这是因为Firebase sdk提供的下载任务是异步的,所以当返回状态意味着被称为uid时,由于任务尚未完成,因此无法设置uid。我如何解决这个问题,以便我得到正确的图片?

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

Firebase下载功能:

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")!
}

1 个答案:

答案 0 :(得分:3)

Firebase是您提到的异步,因此让它驱动您应用中的数据流。

请勿尝试从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
   }
}