Подскажите как вставить и обновить секцию Header в Tableviewcell (Parse)?


#1

Добрый день! Нашел в этой статье для collectionView делают вставку для коллекции картинки https://code-examples.net/ru/q/20c656e .У меня ImagePickerController.Когда пытаюсь в хедер вставить картинку , выдает ошибку.Я понял что она связано с тем что не правильно задал метод добавления. В одном уроке увидел такой пример ,но это старый метод функции .Кто нибудь может подсказать как написать в моем случае? Мне нужно чтоб произошел метод вставки картинки и обновление Хедера и нужная картинка появилась в хедере. self.collectionView.reloadItemsAtIndexPaths(self.collectionView.indexPathsForVisibleItems())

вот пример который нашел.
func lookUpPhotos() {

    let findPhotos = PFQuery(className: "Gallery")
    findPhotos.whereKey("dogID", equalTo: self.dogObjectID)
    findPhotos.orderByDescending("createdAt")
    findPhotos.findObjectsInBackgroundWithBlock { 
        (objects, error) -> Void in

        if let users = objects {
            for object in users { 
                self.photoData.addObject(object)
                print("Fetched \(self.dogSelectedName)'s \(self.photoData.count) Images") 
            } 
        }

        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.reloadData()
        }
    }
}

saveImage.saveInBackgroundWithBlock { (Bool, error) -> Void in
    if error != nil {
        print("There was an error")
    } else {
        print("New Gallery object saved: \(saveImage)")
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.dismissViewControllerAnimated(true) { () -> Void in
                self.lookUpPhotos()
            }
        }
    }
}

Может кто нибудь помочь и поправить меня, немного не хватает опыта и заглох ((((((((.Вот код который я сделал:

import UIKit
import Parse

class UserProfile: UIViewController,UITableViewDelegate,UITableViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
   
  
    var myUser = [PFUser.current()]
    
@objc func updatePhoto() {
        let myPickerImageController = UIImagePickerController()
        myPickerImageController.delegate = self
        myPickerImageController.allowsEditing = true
        myPickerImageController.sourceType = UIImagePickerControllerSourceType.photoLibrary
    
        self.present(myPickerImageController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
      
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileUserHeaderView") as! ProfileUserHeaderView
        if (info [UIImagePickerControllerOriginalImage] as? UIImage) != nil {
            savePhoto(image: header.userFot.image!)
        }
      //  let section = NSIndexSet(index: 0)
      //  self.tableView.reloadSections(section as IndexSet, with: .automatic)
         self.tableView.reloadData()
        picker.dismiss(animated: true, completion: nil)
        
       
        
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }

  var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
    @IBOutlet weak var tableView: UITableView!
    
    
    lazy var refreshControl: UIRefreshControl = {
        let refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Обновление")
    
        refreshControl.addTarget(self, action:
            #selector(UserProfile.handleRefresh(_:)),
                                 for: UIControlEvents.valueChanged)
        refreshControl.tintColor = UIColor.universalColorYellow
       
        return refreshControl
    }()
   

    
   
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        activityIndicator.hidesWhenStopped = true;
    
        activityIndicator.center = view.center;
        super.viewDidLoad()
       
        
        let nib: UINib = UINib(nibName: "ProfileUserHeaderView", bundle: nil)
        tableView.register(nib, forHeaderFooterViewReuseIdentifier: "ProfileUserHeaderView")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Сохранить", style: .plain, target: self, action: #selector(saveBarItem))
        self.navigationController?.navigationBar.tintColor = UIColor.universalColorYellow
        self.navigationController?.navigationItem.title = "Назад"
        
        self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.isTranslucent = true
        self.navigationController!.view.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        
        tableView.addSubview(self.refreshControl)
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
    
        tableView.reloadData()
        loadEditUserInfo()
        
       // loadObjectUser()
        // Do any additional setup after loading the view.
      
        }
        
 /*
func loadObjectUser() {
    
   PFUser.current()!.fetchInBackground(block: { (currentUser, error) -> Void in
        if let user = currentUser as? PFUser {
            user.fetchFromLocalDatastoreInBackground()
            
        }
    })
} */

    

    func segueUser() {
        self.performSegue(withIdentifier: "userprofile", sender: self)
        
    }
   

    

    @objc func saveBarItem() {
        activityIndicator.isHidden = false
        activityIndicator.startAnimating()
        let user = PFUser.current()!
        let indexOne = IndexPath(row: 0, section: 0)
         let indexTwo = IndexPath(row: 1, section: 0)
         let indexThree = IndexPath(row: 2, section: 0)
         let indexFour = IndexPath(row: 3, section: 0)
        let cellOne : UserEditTableViewCell = tableView.cellForRow(at: indexOne) as! UserEditTableViewCell
        let cellTwo : UserEditTableViewCellTwo = tableView.cellForRow(at: indexTwo) as! UserEditTableViewCellTwo
        let cellThree : UserEditTableViewCellThree = tableView.cellForRow(at: indexThree) as! UserEditTableViewCellThree
        let cellFour : UserEditTableViewCellFour = tableView.cellForRow(at: indexFour) as! UserEditTableViewCellFour
         let username = cellOne.userTextField.text!
         let country = cellTwo.countryTextfield.text!
        let email = cellThree.emailTextField.text!
        let password = cellFour.passwordTextField.text!
        user["username"] = username
        user["country"] = country
        user["email"] = email
        user["password"] = password
      
           if PFUser.current()?.password == "" {
            self.alert(message: "Введите пароль", title: "BRAVOBET")
            
        } else {
  
     user.saveInBackground(block: { (success, error) -> Void in
                    if success {
                        Alert.show(textTitle: "BRAVOBET", text: "Вы успешно изменили данные", view: self)
                        self.activityIndicator.isHidden = true
                        self.activityIndicator.stopAnimating()
                        self.tableView.reloadData()
                        self.dismiss(animated: true , completion: nil)
            } else {
               print("Error")
               
            }
        })
        }
    }
    
    func savePhoto(image:UIImage) {
    let imageData = UIImageJPEGRepresentation(image, 0.75)!
        let imageFile = PFFile(data: imageData)
      
        // Upload to Open Source Parse Server which stores the image in an Amazon S3 bucket.
       let userImage = PFUser.current()!
        userImage.setObject(imageFile!, forKey: "profile_picture")
        userImage.saveInBackground { (success, error) in
            if success {
                print("Добавление фото прошло успешо")
            }
        }
    }
    
   
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileUserHeaderView") as! ProfileUserHeaderView
        
        header.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250)
        header.username.text = PFUser.current()!.username
       
         header.buttonSave.addTarget(self, action: #selector(updatePhoto), for: .touchUpInside)
      //  header.bravoBtn.addTarget(self, action: #selector(ProfileUserHeaderView.likeBtn(_:)), for: UIControlEvents.touchUpInside)
        if  header.userFot.image != nil {
            header.userFot.image = UIImage(named: "noFoto")
        } else {
            
            let imagePro: PFFile = PFUser.current()?.object(forKey: "profile_picture") as! PFFile;
            imagePro.getDataInBackground { (data, error) in
                header.userFot.image = error == nil ? UIImage(data: data!) : nil
            }
        }
        
        return header
    }
    
    
  
    
   @IBAction func userSegue(_ sender: UIBarButtonItem) {
        
        self.performSegue(withIdentifier: "pushToUser", sender: self)
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 250
    }
   
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       if  indexPath.row == 0  {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellOne") as! UserEditTableViewCell
        cell.userTextField.text = PFUser.current()!.username
        
           return cell
       } else if indexPath.row == 1 {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTwo") as! UserEditTableViewCellTwo
        cell.countryTextfield.text = PFUser.current()!["country"] as? String
    
        return cell
       } else if indexPath.row == 2 {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellThree") as! UserEditTableViewCellThree
        cell.emailTextField.text = PFUser.current()!.email
        
        return cell
       } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellFour") as! UserEditTableViewCellFour
        cell.passwordTextField.text = PFUser.current()!.password
        
       return cell
        }
       
       
    }
    
    @objc func handleRefresh(_ refreshControl: UIRefreshControl) {
        
        self.tableView.reloadData()
        refreshControl.endRefreshing()
    }
  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    
    func alert(message: NSString, title: NSString) {
        let alert = UIAlertController(title: title as String, message: message as String, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
        
    }
    
    func loadEditUserInfo() {
        
        let userInformation = PFQuery(className: "User")
        userInformation.findObjectsInBackground(block: { (objectUser, error) in
            
            self.myUser = objectUser! as! [PFUser]
            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
                
                
            })
            
            
        })
        
    }
    
    
}