I have an image array var images: NSArray! = [] The maximum number of images in my array is 5 images. I want to be able to work with any number of images, so I extracted them
guard let imageOne = images[0] as? UIImage else { return }
guard let imageTwo = images[1] as? UIImage else { return }
guard let imageThree = images[2] as? UIImage else { return }
guard let imageFour = images[3] as? UIImage else { return }
guard let imageFive = images[4] as? UIImage else { return }
I want each index to be optional, So I can either use imageOne or imageOne and imageTwo but when I try to use less than 5 images, I get an index error. How do I make each index optional so that it is no longer grouped with the array and each index becomes its own image.
I initially have an array because I have a custom UIImagePicker that only takes arrays, but I want to upload the images to Firebase and Firebase does not take arrays, so I have to extract the images from the array.
Using a suggested answer below, I did this to my code:
for (counter, img) in images.enumerated(){
if counter == 0 {
func uploadImage(image: UIImage){
var randomName = randomStringWithLength(length: 5)
let imageData = UIImageJPEGRepresentation(imageOne!, 1.0)
let uploadRef = FIRStorage.storage().reference().child("images/\(randomName).jpg")
uploadRef.put(img as! UIImage, metadata: nil) { metadata,
error in
if error == nil {
print("successfully uploaded Image")
self.imageFileName = "\(randomName as String).jpg"
randomName = randomStringWithLength(length: 5)
let postObject: Dictionary<String, Any> = [
"image" : self.imageFileName,
]
FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).child(key).setValue(postObject)
print("Posted to Firebase. ")
} else{
print("Error uploading image")
}}
}
if let pickedImage = img as?
UIImage{
uploadImage(image: pickedImage)
}
}
}
Now, how do I check to see how many images are selected and call the function within every if counter == num
Although I don't agree with the way you're going about this, this will answer your question:
First change var images: NSArray! = [] to var images: NSMutableArray! = []
while images.count < 5{
images.addObject(UIImage())
}
guard let imageOne = images[0] as? UIImage else { return }
guard let imageTwo = images[1] as? UIImage else { return }
guard let imageThree = images[2] as? UIImage else { return }
guard let imageFour = images[3] as? UIImage else { return }
guard let imageFive = images[4] as? UIImage else { return }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With