uploading images to firebase storage - swift

I am trying to upload two images to firebase storage but it is just uploading one
let imageOne = images[0] as! UIImage
let imageTwo = images[1] as! UIImage
func uploadImage(image: UIImage){
let randomName = randomStringWithLength(length: 5)
let randomNames = randomStringWithLength(length: 9)
let imageData = UIImageJPEGRepresentation(imageOne, 1.0)
let imageDatas = UIImageJPEGRepresentation(imageTwo, 1.0)
let uploadRef = FIRStorage.storage().reference().child("images/\(randomName).jpg")
uploadRef.put(imageData!, metadata: nil) { metadata,
error in
if error == nil {
print("successfully uploaded Image")
AppDelegate.instance().dismissActivityIndicator()
self.imageFileName = "\(randomName as String).jpg"
uploadRef.put(imageDatas!, metadata: nil) { metadata,
error in
if error == nil {
self.imageFileNameTwo = "\(randomNames as String).jpg"
} else{
print("Error uploading image")
}
Only imageOne is uploading. How do I uploading two images at once?

Try like this:
let imageOne = images[0] as! UIImage
let imageTwo = images[1] as! UIImage
func uploadImage(image: UIImage){
let randomName = randomStringWithLength(length: 5)
let randomNames = randomStringWithLength(length: 9)
let imageData = UIImageJPEGRepresentation(imageOne, 1.0)
let imageDatas = UIImageJPEGRepresentation(imageTwo, 1.0)
let uploadRef = FIRStorage.storage().reference().child("images/\(randomName).jpg")
uploadRef.put(imageData!, metadata: nil) { metadata,
error in
if error == nil {
print("successfully uploaded Image")
AppDelegate.instance().dismissActivityIndicator()
self.imageFileName = "\(randomName as String).jpg"
randomName = randomStringWithLength(length: 5)
let uploadRef2 = FIRStorage.storage().reference().child("images/\(randomName).jpg")
uploadRef2.put(imageDatas!, metadata: nil) { metadata,
error in
if error == nil {
self.imageFileNameTwo = "\(randomNames as String).jpg"
} else{
print("Error uploading image")
}
In your code you are uploading 2 images to the one ref.
Hope it helps

I would post as a comment but I don't have enough reputation yet. Why don't you just make the function upload one image as the name suggests, and then call the function twice passing in the first image the first time and then the second image the second time.

Related

App Crashes When saving image to camera roll

When I try saving a scan to the camera roll the app crashes
Here's the Code:
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
// Make sure the user scanned at least one page
guard scan.pageCount >= 1 else {
// You are responsible for dismissing the VNDocumentCameraViewController.
controller.dismiss(animated: true)
return
}
// This is a workaround for the VisionKit bug which breaks the `UIImage` returned from `VisionKit`
// See the `Image Loading Hack` section below for more information.
var arrImages = [UIImage]()
for i in 0...scan.pageCount-1 {
let originalImage = scan.imageOfPage(at: i)
let fixedImage = reloadedImage(originalImage)
arrImages.append(fixedImage)
}
controller.dismiss(animated: true)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("Delete This")
if Filetype == 1 {
let data = createNewPDF(arrImage: arrImages)
do {
try data?.write(to: docURL, options: .completeFileProtection)
print("Success")
} catch(let error) {
print("error is \(error.localizedDescription)")
}
} else {
if Filetype == 2 {
if customjg == 68 {
for i in 0...scan.pageCount-1 {
let originalImage = scan.imageOfPage(at: i)
let fixedImage = originalImage.jpegData(compressionQuality: 0.7)
let reloadedImage = UIImage(data: fixedImage!)
UIImageWriteToSavedPhotosAlbum(reloadedImage!, nil, nil, nil);
//arrImages.append(fixedImage)
}
if customjg == 69 {
let originalImage = scan.imageOfPage(at: 1)
let rere = self.resizeImagezz(image: originalImage, targetSize: CGSize(width: Widthv, height: Heightv))
let fixedImage = rere.jpegData(compressionQuality: 0.7)
let reloadedImage = UIImage(data: fixedImage!)
UIImageWriteToSavedPhotosAlbum(reloadedImage!, nil, nil, nil);
//arrImages.append(fixedImage)
}
}
}else{
if Filetype == 3 {
for i in 0...scan.pageCount-1 {
let originalImage = scan.imageOfPage(at: i)
let fixedImage = originalImage.pngData()
let reloadedImage = UIImage(data: fixedImage!)
UIImageWriteToSavedPhotosAlbum(reloadedImage!, nil, nil, nil);
//arrImages.append(fixedImage)
}
}
}
}
}
The File Type is a segment controlled switch case. The first option by default is JPEG.
It does not even ask for the camera roll access permission before crashing (Yes I've put it in the info.plist file).
Only PDF works as of now.
But the twist is that everything works when installed on iOS 14 Beta.
Please help me rectify this issue As soon as you can.
Thanks for the help in Advance.
As per documentation - https://developer.apple.com/documentation/uikit/1619125-uiimagewritetosavedphotosalbum,
we should implement the completionSelector. and for the same set completionTarget as self.
implement the api as below:
UIImageWriteToSavedPhotosAlbum(reloadedImage!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
then in this completionSelector:
#objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
guard let error = error else {//success return}
// found error
print(error)
}

How can I upload an Image to Firebase with different strings?

In this code Im able to successfully post an image to Firebase. But I would like to add some strings along with it.
#objc func Post(){
print("Post Clicked")
let imageName = "\(NSUUID().uuidString).jpeg"
let imagesFolder = Storage.storage().reference().child("Post")
if let image = imageView.image{
if let imageData : Data = image.jpegData(compressionQuality: 1){
imagesFolder.child(imageName).putData(imageData, metadata: nil) { (metaData, error) in
if let error = error{
print(error)
}else{
imagesFolder.child(imageName).downloadURL { (url, error) in
if let imageURL = url?.absoluteString{
self.imageURL = imageURL
print("Success")
}
}
}
}
}
}
}
How can I upload these custom strings from UILabels along with the same image? I have tried placing this code in different areas of the Post function but it does not work. What is the proper way to do this?
//([
//"Title" : titleLabel.text,
//"Article" : articleLabel.text,
//"Author" : authorLabel.text,
//"Date" : DateLabel.text,
//])

Having trouble understanding why my app crashes

I'm trying to upload an image to the Firebase storage. This is what I have so far:
fileprivate func uploadImageToFirebase(){
let storageRef = Storage.storage().reference()
guard let uploadData = imageToUpload?.pngData() else { return }
storageRef.putData(uploadData, metadata: nil) { (metadata, err) in
if err != nil {
print(err?.localizedDescription)
return
}
print(metadata)
}
}
uploadData is not nil, but my app crashes. this is what I get:
reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
I tried to look up, but couldn't understand why the app crash and how to fix it.
I got it that I'm trying to insert a nil, but I don't have anything nil.
I got it to work, this is what I have now:
fileprivate func uploadImageToFirebase(completion: #escaping((_ url: String?)->())){
let imageName = UUID().uuidString
let storageRef = Storage.storage().reference()
let imagesRef = storageRef.child(imageName)
guard let uploadData = imageToUpload?.jpegData(compressionQuality: 0.8) else { return }
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
imagesRef.putData(uploadData, metadata: metaData) { (metadata, err) in
if err == nil && metadata != nil {
imagesRef.downloadURL(completion: { (url, err) in
guard let downloadUrl = url else { return }
let urlString = downloadUrl.absoluteString
completion(urlString)
})
}
completion(nil)
}
}
EDIT:
The problem with the code in the question was there was no name assigned to the file to upload. In other words
let storageRef = Storage.storage().reference()
is a reference to the storage itself, but when uploading to storage there needs to be a filename like this
let storageRef = Storage.storage().reference()
let myFile = storageRef.child("my_cool_pic.jpg")
and the use is
myFile.putData(uploadData, metadata: nil)...

How to store image from uiimageView in firebase

func uploadImage(){
let data = Data()
let storage = Storage.storage()
let storageRef = storage.reference()
let imagesRef = storageRef.child(imageView.image) //not sure how it's done
let uploadTask = imagesRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imagesRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
}
Hi,I'm new to xcode. I would love to know how to upload image displayed on uiimageview to firebase when the above function is called.
you can do something like this:
func uploadImage(img1 :UIImage){
var data = NSData()
data = UIImageJPEGRepresentation(img1!, 0.8)! as NSData
// setting the upload path
// then choose the path where you want to store the image in the storage
let filePath = "\(userid)"
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef = FIRStorage.storage().reference()
self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//Storing the downloadURL..
let downloadURL = metaData!.downloadURL()!.absoluteString
}
}
}

Use Facebook profile picture as you profile picture Swift

I am getting facebook's profile picture and displaying it as the profile picture in my app. Here is the code.
if let user = FIRAuth.auth()?.currentUser{
let photoUrl = user.photoURL
let name = user.displayName
self.FacebookUser.text = name
let storage = FIRStorage.storage()
//refer your particular storage service
let storageRef = storage.reference(forURL: "gs://gsignme-14416.appspot.com")
let profilePicRef = storageRef.child(user.uid+"/profile_pic.jpg")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) -> Void in
if (error == nil){
self.FacebookPic.image = UIImage(data: data!)
}else{
print("Error downloading image:" )
}
})
if(self.FacebookPic.image == nil)
{
var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height": 300, "width": 300, "redirect": false], httpMethod: "GET")
profilePic?.start(completionHandler: {(_ connection, result, error) -> Void in
// Handle the result
if error == nil {
if let dictionary = result as? [String: Any],
let data = dictionary["data"] as? [String:Any],
let urlPic = data["url"] as? String{
if let imageData = NSData(contentsOf: NSURL(string: urlPic)!as URL){
let uploadTask = profilePicRef.put(imageData as Data, metadata: nil) {
metadata, error in
if (error == nil)
{
let downloadurl = metadata!.downloadURL
}
else
{
print("Error in downloading image")
}
}
self.FacebookPic.image = UIImage(data: imageData as Data)
}}}})}
}else{
}
//The END of the Facebook user and picture code
I was able to get it working for a couple days and now it doesn't work anymore, I have gone through it line by line and I honestly can't figure out why it is not working.
I used this code:
func pictureFromFirebase(loginMethod: Int)
{
if loginMethod == 0 //FB
{
var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height":300, "width":300, "redirect":false], httpMethod: "GET")
let profilePicRef = storageRef.child((user?.uid)!+"/profile_pic.jpg")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
// but we don't need to do anything yet. Try to download the profile pic
}
if (data != nil)
{
print("no need to download image from facebook")
self.profileImage.image = UIImage (data: data!)
}
else
{
// THIS IS THE BLOCK THAT HAS BEEN MOVED
// WHICH WILL NOW BE EXECUTED IN TWO CONDITIONS -
// 1. AN ERROR IN THE DOWNLOAD
// 2. NO PROFILE PIC AVAILABLE
print("downloading image from facebook")
profilePic?.start(completionHandler: {(_ connection, _ result, _ error) -> Void in
if (error == nil)
{
if let dictionary = result as? [String:Any], let data = dictionary["data"] as? [String:Any],
let urlPic = data["url"] as? String {
if let imageData = NSData(contentsOf: NSURL(string: urlPic)! as URL)
{
let uploadTask = profilePicRef.put(imageData as Data, metadata: nil){
metadata, error in
if (error == nil)
{
let downloadUrl = metadata!.downloadURL
}
else
{
print("error in downloading image")
}
}
self.profileImage.image = UIImage(data: imageData as Data)
}
}
}
})
}
}
}
}
from this post Second If statement gets called before first statement finished in one function and it worked
you just get your facebook profile pic. using this url and put the url in your UIImageview
let profilepicURl = "https://graph.facebook.com/\(user_id_fb)/picture?type=large" //user_id_fb like 1251246454544 your facebook ID