【发布时间】: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")!
}
【问题讨论】:
-
参考answer。
-
@Dershowitz123 是的,但是返回状态意味着将在完成之前调用我想在这一点上保留函数
-
也看到这个问题,我参考的答案:stackoverflow.com/questions/38547875/…
标签: ios swift xcode asynchronous firebase