我正在创建一个像instagram这样的应用程序,并在tableview中有一个帖子列表.Posts是通过json从服务器解析下载的。每个帖子在服务器上都有唯一的帖子ID。 每个帖子都有一个喜欢和评论按钮。
PRoblem声明:如何获取特定单元格的post id,以便我可以在按钮和注释按钮操作中使用它。
这就是我在做的事情:
内部文件:PostDataTableVIewCell.swift -
@IBAction func likeBtnPressed(_ sender: AnyObject) {
if !pressed {
let image = UIImage(named: "Like-1.png") as UIImage!
likeBtn.setImage(image, for: .normal)
pressed = true
}
else
{
// let buttonPosition:CGPoint = (sender as AnyObject).convert(
// let indexPath = maincell.feedTable.indexPathForRow(at: buttonPosition)
let image = UIImage(named: "liked.png") as UIImage!
likeBtn.transform = CGAffineTransform(scaleX: 0.15, y: 0.15)
UIView.animate(withDuration: 2.0,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: .allowUserInteraction,
animations: { [weak self] in
self?.likeBtn.transform = .identity
},
completion: nil)
likeBtn.setImage(image, for: .normal)
pressed = false
likeUpdateServer()
}
}
在更新中的功能 -
func likeUpdateServer()
{
let userDefaults = UserDefaults.standard
let value = userDefaults.string(forKey: "api_token")
let api_token : String! = value
let post_id = userDefaults.string(forKey: "postIDofPost")
print(api_token)
print(post_id!)
var request = URLRequest(url: URL(string: "\(URL_BASE)\(LIKEPOST)")!)
request.httpMethod = "POST"
let postString = "api_token=\(api_token!)&&post_key=\(post_id!)"
print("\(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
print("cant run")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
else {
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
}
task.resume()
}