Swift 3 How to correctly write Completion Handler Block

2.9k views Asked by At

I am new to Xcode and programming languages and I need your help. I am working on a Message application and I'm unable to use a Completion Handler Block. Here is my code :

     @IBAction func SendButton(_ sender: AnyObject) {


    if self.textfield.text != "" {


        let mess = CKRecord(recordType: "Message")
        mess["content"] = textfield.text as CKRecordValue?

        let publicdata = CKContainer.default().publicCloudDatabase

        publicdata.save(mess, completionHandler: {(record, error) -> Void in
            if error == nil {


                let indexpath = NSIndexPath(item: self.chat.count, section: 0)


                CATransaction.begin()
                CATransaction.setDisableActions(true)


                self.CollView.performBatchUpdates ({

                    self.chat.insert(mess, at: self.chat.count)
                    self.CollView.insertItems(at: [indexpath as IndexPath])


                }, completion: {(true) -> Void in

                print("Animation completed")
                self.CollView.contentOffset = CGPoint(x: 0, y: 40)

                })

                CATransaction.commit()

            print("SAVED")


            }else{
            print("error")
            }})

    }

    textfield.text = ""
}

I use CATransaaction to performBatchUpdates, but the Completion Handler Block in the performBatchUpdates method can't be completed. As you can see, it's not the right way to write it and I know it, but I've tried everything I know to achieve it but it won't. The completion :

 completion: {(true) -> Void in

            print("Animation completed")
            self.CollView.contentOffset = CGPoint(x: 0, y: 40)

            })

Please help me. Thank you !!

2

There are 2 answers

0
Liberitus On

you can try this

collectionView?.performBatchUpdates({
                print("First part")
            }, completion: { (result: Bool) in
                print("Second part")
            })
0
XLegare On
 func loadData() {
    chat = [CKRecord]()


let publicData = CKContainer.default().publicCloudDatabase


    let query = CKQuery(recordType: "Message", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    publicData.perform(query, inZoneWith: nil, completionHandler: {(results, error) -> Void in

        if let text = results {
        self.chat = text
            DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { () -> Void in
                self.CollView.reloadData()
            }


        }else{
        print("error")
        }


    })

}