如何检索存储在firebase中的图像以在视图图像视图中显示 [英] how to Retrieve image stored in firebase to show it in view image view
问题描述
如何检索存储在firebase
中的图像?@IBAction func AddDeviceButton(sender:AnyObject){
if DeviceName.text ==|| Description.text ==|| ImageView.image == nil {
let alert = UIAlertController(title:عذرا,message:يجبععموماتالجهازكاملة,preferredStyle:.Alert)
alert.addAction(UIAlertAction(title: نعم,style:.Default){_in})
self.presentViewController(alert,animated:true){}
$ b $} else {
let imageName = NSUUID()。UUIDString
let storageRef = FIRStorage.storage()。reference()。child(Devices_Images)。child(\(imageName).png)
让metaData = FIRStorageMetadata()
metaData.contentType =image / png
如果让uploadData = UIImagePNGRepresentation(self.ImageView.image!){
storageRef.putData uploadData,元数据:metaData,完成:
中的{(数据,错误)if error!= nil {
print(error)
} else {
print 图片上传成功y)
let profileImageUrl = data?.downloadURL()?。absoluteString
//
让DeviceInfo = [
ImageUrl:profileImageUrl !,
DeviceName:self.DeviceName.text !,
Description:self.Description.text !,
Category:self.itemSelected
]
让DeviceInformation = [
ImageUrl:profileImageUrl !,
DeviceName:self.DeviceName.text !,
Description:self.Description.text! ,
Category:self.itemSelected,
name:self.globalUserName,
email:self.globalEmail,
city:self.globalCity,
电话:self.globalPhone
]
self.ref.child(Devices)。child(FIRAuth.auth()!. currentUser!.uid).observeSingleEventOfType(.Value,withBlock:{(snapShot)
if snapShot.exists(){
let numberOfDevicesAlreadyInTheDB = snapShot.childrenCount
if numberOfDevicesAlreadyInTheDB< 3 {
let newDevice = String(Device \(numberOfDevicesAlreadyInTheDB + 1))
let userDeviceRef = self.ref.child(Devices)。child(FIRAuth.auth()!. currentUser !.uid)
userDeviceRef.observeSingleEventOfType(.Value,withBlock:{(userDevices)in
if userDeviceDict = userDevices.value as?NSMutableDictionary {
userDeviceDict.setObject(DeviceInfo ,forKey:newDevice)
$ b $ userDeviceRef.setValue(userDeviceDict)
}
})
}
else {
let alert = UIAlertController标题:عذرا,留言:偏好的方式 b $ b alert.addAction(UIAlertAction(title:نعم,style:.Default){_in})
self.presentViewController(alert,animated:true){}
}
(设备1:设备信息])
self.ref .child(UserDevices)。childByAutoId().setValue(DeviceInformation)
$ b})
//
} })
}
} // Big Big El
} // AddDeviceButton
我只是想将图片加载到Firebase存储中的用户个人资料中,以便每次用户登录他的个人资料时,他都可以看到他上传到应用程序的所有图片。 p>
我们高度推荐最终使用Firebase存储和Firebase实时数据库来完成此操作。以下是一个完整的示例:
共享:
// Firebase服务
var database:FIRDatabase!
var storage:FIRStorage!
...
//初始化数据库,Auth,存储
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
//为你的图片初始化一个数组
var picArray:[UIImage]()
let myUserId = ... //从Firebase Auth或其他一些ID提供者获取
<
上传:
let fileData = NSData()//获取数据...
let storageRef = storage.reference()。child(userFiles / \(myUserId)/ myFile)
storageRef.putData(fileData)。 observeStatus(.Success){(snapshot)in
//当图片成功上传时,我们得到它的下载URL
让downloadURL = snapshot.metadata?.downloadURL()?。absoluteString
//将下载URL写入实时数据库
let dbRef = database.reference()。child(userFiles / \(myUserId)/ myFile)
dbRef.setValue(downloadURL)
下载:
let dbRef = database.reference() .child(userFiles / \(myUserId))
dbRef.observeEventType(.ChildAdded,withBlock:{(snapshot)in
//从快照获取下载网址
让downloadURL =快照.value()as! String
//从URL创建存储引用
let storageRef = storage.referenceFromURL(downloadURL)
//下载数据,假设最大大小为1MB(可以根据需要更改)
storageRef.dataWithMaxSize(1 * 1024 * 1024){(data,error) - > void
//创建一个UIImage,将它添加到数组
let pic = UIImage(data:data)
picArray.append(pic)
})
})
有关详情,请参阅零到应用程序:使用Firebase开发,它是相关的源代码,一个实际的例子如何做到这一点。
i am facing a problem with how to retrieve an image stored in firebase
here is the code i used to store the image :
@IBAction func AddDeviceButton(sender: AnyObject) {
if DeviceName.text == "" || Description.text == "" || ImageView.image == nil {
let alert = UIAlertController(title: "عذرًا", message:"يجب عليك تعبئة معلومات الجهاز كاملة", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
} else {
let imageName = NSUUID().UUIDString
let storageRef = FIRStorage.storage().reference().child("Devices_Images").child("\(imageName).png")
let metaData = FIRStorageMetadata()
metaData.contentType = "image/png"
if let uploadData = UIImagePNGRepresentation(self.ImageView.image!) {
storageRef.putData(uploadData, metadata: metaData, completion: { (data, error) in
if error != nil {
print(error)
} else {
print("Image Uploaded Succesfully")
let profileImageUrl = data?.downloadURL()?.absoluteString
//
let DeviceInfo = [
"ImageUrl":profileImageUrl!,
"DeviceName":self.DeviceName.text!,
"Description":self.Description.text!,
"Category":self.itemSelected
]
let DeviceInformation = [
"ImageUrl":profileImageUrl!,
"DeviceName":self.DeviceName.text!,
"Description":self.Description.text!,
"Category":self.itemSelected,
"name": self.globalUserName,
"email":self.globalEmail ,
"city": self.globalCity,
"phone": self.globalPhone
]
self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEventOfType(.Value, withBlock: {(snapShot) in
if snapShot.exists(){
let numberOfDevicesAlreadyInTheDB = snapShot.childrenCount
if numberOfDevicesAlreadyInTheDB < 3{
let newDevice = String("Device\(numberOfDevicesAlreadyInTheDB+1)")
let userDeviceRef = self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid)
userDeviceRef.observeSingleEventOfType(.Value, withBlock: {(userDevices) in
if let userDeviceDict = userDevices.value as? NSMutableDictionary{
userDeviceDict.setObject(DeviceInfo,forKey: newDevice)
userDeviceRef.setValue(userDeviceDict)
}
})
}
else{
let alert = UIAlertController(title: "عذرًا", message:"يمكنك إضافة ثلاثة أجهزة فقط كحد أقصى", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
}else{
self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Device1" : DeviceInfo])
self.ref.child("UserDevices").childByAutoId().setValue(DeviceInformation)
}
})
//
} })
}
} //Big Big Else
} //AddDeviceButton
i just wanna load the images to user profile from the firebase storage so that every time user logged into his profile he can see all images he uploads to the application
解决方案 We highly recommend using Firebase Storage and the Firebase Realtime Database together to accomplish this. Here's a full example:
Shared:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()
let myUserId = ... // get this from Firebase Auth or some other ID provider
Upload:
let fileData = NSData() // get data...
let storageRef = storage.reference().child("userFiles/\(myUserId)/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("userFiles/\(myUserId)/myFile")
dbRef.setValue(downloadURL)
}
Download:
let dbRef = database.reference().child("userFiles/\(myUserId)")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
})
})
For more information, see Zero to App: Develop with Firebase, and it's associated source code, for a practical example of how to do this.
这篇关于如何检索存储在firebase中的图像以在视图图像视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!