0

I am new to IOS. I am building an image sharing app with Xcode and Swift

I am stuck in images uploading part.

How can I limit users to choose 8 images at most and then upload the chosen pictures to Firebase using a For-loop?

I would like to use For-loop since I want to set the first picture as an icon picture.

Below is what I am able to do now

I created a SignUp page and allow a user to use ImagePicker to select 1 image and upload it to Firebase. Below is my code.

import UIKit
import Firebase

class SignUpViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
{

    @IBOutlet weak var iconfield: UIImageView!

    @IBOutlet weak var usernamefield: UITextField!

    @IBOutlet weak var emailfield: UITextField!

    @IBOutlet weak var passwordfield: UITextField!

    @IBOutlet weak var confirmpasswordfield: UITextField!

    @IBOutlet weak var signupbutton: UIButton!

    let picker = UIImagePickerController()
    var userStorage: StorageReference!
    var ref: DatabaseReference!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        picker.delegate = self
        let storage = Storage.storage().reference(forURL: "gs://whatisit-8484a.appspot.com/")
        ref = Database.database().reference()
        userStorage = storage.child("users")
        // Do any additional setup after loading the view.
        iconfield.layer.cornerRadius=iconfield.frame.size.width/2
        iconfield.clipsToBounds = true
    }

    @IBAction func selectionpressed(_ sender: Any)
    {
        picker.allowsEditing = true
        picker.sourceType = .photoLibrary
        present(picker,animated:true,completion:nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage
        {
            self.iconfield.image = image
            signupbutton.isHidden = false
        }
        self.dismiss(animated:true,completion:nil)
    }

    @IBAction func confirmsignup(_ sender: Any)
    {
        guard usernamefield.text != "",emailfield.text != "",passwordfield.text != "", confirmpasswordfield.text != "" else {return}

        if passwordfield.text == confirmpasswordfield.text
        {
            Auth.auth().createUser(withEmail: emailfield.text!, password: passwordfield.text!, completion: { (user, error) in
                if let error = error
                {
                    print(error.localizedDescription)
                }

                if let user = user
                {
                    let changeRequest = Auth.auth().currentUser!.createProfileChangeRequest()
                    changeRequest.displayName = self.usernamefield.text!
                    changeRequest.commitChanges(completion: nil)

                    let imageRef = self.userStorage.child("\(user.uid).jpg")
                    let data = UIImageJPEGRepresentation(self.iconfield.image!, 0.5)

                    let uploadTask = imageRef.putData(data!, metadata: nil, completion: { (metadata, err) in
                        if err != nil{
                            print(err!.localizedDescription)
                        }
                        imageRef.downloadURL(completion: { (url, er) in
                            if er != nil{
                                print(er!.localizedDescription)
                            }

                            if let url = url
                            {
                                let userInfo: [String: Any] = ["uid": user.uid,"E-mail":self.emailfield.text,"username": self.usernamefield.text,"urlToImage": url.absoluteString]
                                self.ref.child("users").child(user.uid).setValue(userInfo)
                                let vc = UIStoryboard(name: "Main",bundle:nil).instantiateViewController(withIdentifier: "homeview")
                                self.present(vc,animated:true,completion:nil)
                            }
                        })
                    })
                    uploadTask.resume()
                }
            })
        }
halfer
  • 19,824
  • 17
  • 99
  • 186
Ricky Sze
  • 1
  • 2
  • 5
    Welcome to StackOverflow Ricky. In order to get a good answer, it's best to ask a good question. Please show/explain what you have tried already, what code you have so far and what is wrong with your current implementation. We can then guide you based on what you have – Scriptable Mar 16 '18 at 13:04
  • As firebase functions are asynchronous so loop will not work here. Use a recursion instead. Make a function to upload the image and after successfully uploading call that function again with next image. – TheTiger Mar 16 '18 at 13:14

1 Answers1

0

Your question is quite broad and actually covers a few different questions. Really, you should break the problem down and only post a question for each, but I will give you some guidance.

  • How to select multiple images using a UIImagePickerController - Basically you can't, you either need to use a library or do your own implementation using the PhotoLibrary
  • How to upload an image to Firebase should be fairly straight forward.
  • Multiple uploads can be a bit more complex. You could use a NSOperationQueue to manage a queue of items to process and specify how many to handle at once, you could use a SerialQueue to process items one at a time or a DispatchQueue to fire all of the requests at once and it will let you know when it finishes. Once you reach this point, firstly give it a try, look into the mentioned methods. If you get stuck, raise another question and explain your approach, how you want it to work and what is going wrong.

This other answer may help with the multiple uploads, if not have a look for Grand Central Dispatch online or check here

Scriptable
  • 19,402
  • 5
  • 56
  • 72