我正在试用firebase存储功能,我无法在imageview中显示下载的图像。下载成功但没有显示。如果我使用资产中的图像,它确实显示。为什么这不起作用?
DownloadViewController:
import UIKit
import FirebaseStorage
import Firebase
@objc(DownloadViewController)
class DownloadViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var statusTextView: UITextView!
var storageRef: FIRStorageReference!
override func viewDidLoad() {
super.viewDidLoad()
storageRef = FIRStorage.storage().reference()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = "file:\(documentsDirectory)/myimage.jpg"
let storagePath = UserDefaults.standard.object(forKey: "storagePath") as! String
// [START downloadimage]
storageRef.child(storagePath).write(toFile: URL.init(string: filePath)!,
completion: { (url, error) in
if let error = error {
print("Error downloading:\(error)")
self.statusTextView.text = "Download Failed"
return
}
self.statusTextView.text = "Download Succeeded!"
print("filepath: "+filePath)
let image = UIImage.init(contentsOfFile: filePath)
self.imageView.image = image
self.imageView.layoutIfNeeded()
self.imageView.clipsToBounds = true
})
// [END downloadimage]
}
}
答案 0 :(得分:0)
尝试在功能块的末尾添加.resume,如下所示:
})。恢复
答案 1 :(得分:0)
我认为这里的问题是您的文件不存在:
let filePath = "file:\(documentsDirectory)/myimage.jpg"
可能没有解析到正确的用户文档目录,你应该使用类似的东西(原谅Obj-C,已经用它回答了这个问题):
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"hello"] URLByAppendingPathExtension:@"txt"];
这也可以防止"在模拟器上运行但在设备上不起作用的问题"反之亦然。