You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于WordPress后端的Swift iOS应用添加评论提交功能求助

Add Comment Submission Feature to Your WordPress iOS App

Got it, let's walk through implementing the comment input and submission functionality step by step. Here's exactly what you need to do to add this feature to your existing app:


1. Add Comment Input UI to CommentViewController

First, we'll add a multi-line text input and a submit button at the bottom of your screen, plus handle keyboard layout so the input doesn't get hidden.

Update your CommentViewController with these additions:

// Add these properties at the top of the class
var commentInputView: UITextView!
var submitButton: UIButton!
var postId: Int! // We need this to link comments to the correct post

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Comments"
    
    // ... Keep your existing navigation bar setup code here ...
    
    // Add the comment input UI first (so it stays above keyboard)
    setupCommentInputUI()
    
    // Check if post has comments (your existing code)
    if(self.dataArray.count == 0){
        self.view.backgroundColor = UIColor(red: 216 / 255, green: 216 / 255, blue: 216 / 255, alpha: 1.0)
        let label = UILabel(frame: CGRect(x: (UIScreen.main.bounds.width/2)-100, y: (UIScreen.main.bounds.height/2)-50, width: 200, height: 50))
        label.text = "No Comments"
        label.font = UIFont(name: "SFUIText-Regular", size: 18)
        label.textAlignment = NSTextAlignment.center
        self.view.addSubview(label)
    } else{
        self.setupTable()
    }
    
    // Listen for keyboard changes to adjust layout
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

// Setup the input text view and submit button
func setupCommentInputUI() {
    // Submit Button
    submitButton = UIButton(type: .system)
    submitButton.setTitle("Submit Comment", for: .normal)
    submitButton.titleLabel?.font = UIFont(name: "SFUIText-Medium", size: 16)
    submitButton.addTarget(self, action: #selector(submitCommentTapped), for: .touchUpInside)
    submitButton.translatesAutoresizingMaskIntoConstraints = false
    
    // Comment Input Text View
    commentInputView = UITextView()
    commentInputView.layer.borderWidth = 1
    commentInputView.layer.borderColor = UIColor.lightGray.cgColor
    commentInputView.layer.cornerRadius = 4.0
    commentInputView.font = UIFont(name: "SFUIText-Regular", size: 16)
    commentInputView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    commentInputView.translatesAutoresizingMaskIntoConstraints = false
    commentInputView.text = "Write your comment here..."
    commentInputView.textColor = .lightGray
    commentInputView.delegate = self // Handle placeholder behavior
    
    // Add views to the screen
    self.view.addSubview(commentInputView)
    self.view.addSubview(submitButton)
    
    // AutoLayout constraints (pin to bottom, avoid keyboard)
    NSLayoutConstraint.activate([
        commentInputView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
        commentInputView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
        commentInputView.bottomAnchor.constraint(equalTo: submitButton.topAnchor, constant: -8),
        commentInputView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80),
        
        submitButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
        submitButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -8),
        submitButton.heightAnchor.constraint(equalToConstant: 40)
    ])
}

// Handle placeholder for the text view
extension CommentViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == "Write your comment here..." && textView.textColor == .lightGray {
            textView.text = ""
            textView.textColor = .black
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Write your comment here..."
            textView.textColor = .lightGray
        }
    }
}

// Adjust layout when keyboard appears/hides
@objc func keyboardWillShow(notification: NSNotification) {
    guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
    let keyboardHeight = keyboardFrame.height
    
    commentInputView.bottomAnchor.constraint(equalTo: submitButton.topAnchor, constant: -8).isActive = false
    commentInputView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -keyboardHeight - 16).isActive = true
    view.layoutIfNeeded()
}

@objc func keyboardWillHide(notification: NSNotification) {
    commentInputView.bottomAnchor.constraint(equalTo: submitButton.topAnchor, constant: -8).isActive = false
    commentInputView.bottomAnchor.constraint(equalTo: submitButton.topAnchor, constant: -8).isActive = true
    view.layoutIfNeeded()
}

Also, update the parent view controller to pass the post ID when pushing CommentViewController:

@IBAction func commentViewController(_ sender: Any) { 
    let vc = CommentViewController() 
    vc.dataArray = jsonData["comments"].array 
    vc.postId = jsonData["id"].intValue // Pass the post's ID here
    self.navigationController!.pushViewController(vc, animated: true) 
}

2. Implement WordPress Comment Submission API Call

WordPress REST API uses the endpoint wp-json/wp/v2/comments to create comments. Add this function to handle the POST request:

@objc func submitCommentTapped() {
    guard let postId = postId else { return }
    let commentContent = commentInputView.text.trimmingCharacters(in: .whitespacesAndNewlines)
    
    // Validate input
    guard !commentContent.isEmpty && commentContent != "Write your comment here..." else {
        showAlert(title: "Oops", message: "Please enter a comment first")
        return
    }
    
    // Note: Add name/email input fields if you don't have them already
    let userName = "Your Name" // Replace with user input or stored value
    let userEmail = "your@email.com" // Replace with user input or stored value
    
    guard !userName.isEmpty && !userEmail.isEmpty else {
        showAlert(title: "Oops", message: "Please enter your name and email")
        return
    }
    
    // Prepare API request
    guard let url = URL(string: "https://your-wordpress-site.com/wp-json/wp/v2/comments") else { return }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let parameters: [String: Any] = [
        "post": postId,
        "author_name": userName,
        "author_email": userEmail,
        "content": commentContent
    ]
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
    } catch {
        print("Error formatting comment data: \(error.localizedDescription)")
        return
    }
    
    // Send the request
    let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
        guard let self = self else { return }
        
        DispatchQueue.main.async {
            if let error = error {
                self.showAlert(title: "Submission Failed", message: error.localizedDescription)
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                self.showAlert(title: "Submission Failed", message: "Something went wrong. Please try again later.")
                return
            }
            
            // Clear input field
            self.commentInputView.text = "Write your comment here..."
            self.commentInputView.textColor = .lightGray
            
            // Refresh comments list to show the new comment
            self.refreshComments()
        }
    }
    task.resume()
}

// Helper to show error alerts
func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
}

// Refresh comments after successful submission
func refreshComments() {
    guard let postId = postId else { return }
    guard let url = URL(string: "https://your-wordpress-site.com/wp-json/wp/v2/comments?post=\(postId)") else { return }
    
    let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
        guard let self = self, let data = data else { return }
        
        do {
            let newComments = try JSON(data: data)
            self.dataArray = newComments.array
            DispatchQueue.main.async {
                if self.dataArray.count == 0 {
                    // Update empty state if needed
                } else {
                    self.tableView.reloadData()
                    // Scroll to top to show the new comment
                    self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                }
            }
        } catch {
            print("Error loading comments: \(error.localizedDescription)")
        }
    }
    task.resume()
}

3. Key Notes to Adjust

  • Replace https://your-wordpress-site.com with your actual WordPress site URL.
  • If your site requires authentication for comments, add an authorization header to the POST request (e.g., using a WordPress REST API key).
  • Add separate input fields for name and email if you don’t already collect that info (you can add them above the comment text view in setupCommentInputUI).
  • Consider disabling the submit button during the API request to prevent duplicate submissions.

内容的提问来源于stack exchange,提问作者Ninder Chand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:42:45