1

I have a function called loadPosts that returns an array of Int values. Upon running it is used within the UITableView which has a function called setCell. Only the first item in the array is being used and then it repeats that value for the length of the array.

UPDATE 2: Here are the parameters within the hhmessages array: 1. senderusername 2. recipient 3. message text 4. ava image

UPDATED: now includes additional code in loadPosts function

func loadPosts()->[Int] {
    let me = user!["username"] as! String
    let uuid = messages["uuid"] as! String
    let url = URL(string: "http://localhost/message.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "username=\(me)&uuid=\(uuid)"
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    self.hhmessages.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    // declare new parseJSON to store json
                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let messages = parseJSON["messages"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                    }

                    self.hhmessages = messages
                    //print(self.hhmessages)

for i in 0 ..< self.hhmessages.count {
     if me == self.hhmessages[i]["senderusername"]!! as! String {
         self.incoming = [0]
 }
     if me == self.hhmessages[i]["recipient"]!! as! String {
         self.incoming = [1]
   }
}
self.tableView.reloadData()
return [Int()]
}

// UITableView

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell

    func setCell(incoming: [Int]) {

        var layoutAttribute: NSLayoutAttribute
        var layoutConstant: CGFloat
        for i in 0 ..< self.incoming.count {

            if (self.incoming[i] == 1) {
                cell.bubbleImageView.image=#imageLiteral(resourceName: "chat_bubble_received")
            cell.messageLbl.textColor = UIColor.black
            layoutAttribute = .left
            layoutConstant = 10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))
        }
           if (self.incoming[i] == 0) {
                cell.bubbleImageView.image = #imageLiteral(resourceName: "chat_bubble_sent")
        cell.messageLbl.textColor = UIColor.white
            layoutAttribute = .right
            layoutConstant = -10
        cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))

        }
        }
    }
    // get main queue to this block of code to communicate back
    DispatchQueue.main.async {

        tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
        cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
        setCell(incoming: self.incoming)

    }
    return cell
}
13
  • your return integer array is correct ? do you mind to post an example of your hhmessages ? Commented Apr 6, 2018 at 20:53
  • @GIJOW thank you for responding. Sure I can post the hhmessages. I know the hhmessages are working as I can see the messages, they just aren't formatted based on the conditions set in setCell Commented Apr 6, 2018 at 21:00
  • @GIJOW I've included the additional code for hhmessages Commented Apr 9, 2018 at 21:51
  • sorry about the misunderstanding but I meant some content of hhmessages to understand the structure Commented Apr 9, 2018 at 22:06
  • 1
    @NateBirkholz thank you Nate. I truly appreciate any help you can provide. I'm fairly new so I'm just happy you responded. I'm determine the number of rows by the hhmessages.count. hhmessages holds the array values. Does that make sense? Commented Apr 9, 2018 at 22:46

1 Answer 1

1
func loadPosts()->[Int] {
    let me = user!["username"] as! String
    let uuid = messages["uuid"] as! String
    let url = URL(string: "http://localhost/message.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "username=\(me)&uuid=\(uuid)"
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    self.hhmessages.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    // declare new parseJSON to store json
                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let messages = parseJSON["messages"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                }

                    self.hhmessages = messages
                    //print(self.hhmessages)

                    /// This is the part I edited
                    for i in 0 ..< self.hhmessages.count {
                        if me == self.hhmessages[i]["senderusername"]!! as! String {
                            self.incoming.append(0)
                        }
                        if me == self.hhmessages[i]["recipient"]!! as! String {
                            self.incoming.append(1)
                        }
                    }
                    self.tableView.reloadData()
                    return [Int()]
 }

Change your cellForRowAt to use the indexPath.row as the index for self.incoming :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell

    func setCell(incoming: [Int]) {

        var layoutAttribute: NSLayoutAttribute
        var layoutConstant: CGFloat

        if (self.incoming[indexPath.row] == 1) {
            cell.bubbleImageView.image=#imageLiteral(resourceName: "chat_bubble_received")
            cell.messageLbl.textColor = UIColor.black
            layoutAttribute = .left
            layoutConstant = 10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))
        }
        if (self.incoming[indexPath.row] == 0) {
            cell.bubbleImageView.image = #imageLiteral(resourceName: "chat_bubble_sent")
            cell.messageLbl.textColor = UIColor.white
            layoutAttribute = .right
            layoutConstant = -10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))

        }
    }
// get main queue to this block of code to communicate back
    DispatchQueue.main.async {

        tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
        cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
        setCell(incoming: self.incoming)

    }
    return cell
}
Sign up to request clarification or add additional context in comments.

7 Comments

thank you so much for helping me. I went through the results. hhmessages has 54 rows (messages), incoming should be 1 a total of 7 times based on the data and 0 the remaining. I incorporate your awesome suggestion but it resulted in a sequence of 1s and 0s that looped through 54 times. The conditional formatting still didn't go through. It's as if the first 'incoming' gets to the formatting condition but no others. Make sense?
@techgirl I'm very puzzled. Your layout code looks like it should be working! I'm going to try to recreate your project based on what I know so far. This should take a little bit though. :)
I'm sorry for the confusion. :(
@techgirl figured it out, I should have seen it sooner, silly me. Check out the revised answer
IT WORKED. You're the real MVP. Thank you so so much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.