【问题标题】:swift Firebase return in asynchron Task在异步任务中快速返回 Firebase
【发布时间】:2016-07-24 09:38:11
【问题描述】:

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

【问题讨论】:

标签: ios swift xcode asynchronous firebase


【解决方案1】:

正如您所提到的,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
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2021-08-22
    • 2019-02-16
    • 1970-01-01
    • 2015-01-12
    • 2014-10-01
    相关资源
    最近更新 更多