@IBAction func followUser(_ sender: Any) {
if followBtn.titleLabel?.text == "Follow"{
print("will follow")
} else if followBtn.titleLabel?.text == "Following"{
}
}
有更好的方法吗?我有一个函数,负载运行然后检查是否跟随用户并更改按钮的文本。当然,如果按钮显示“跟随”,它将具有与“跟随”按钮不同的功能。这是我能做到的唯一方法吗?感觉不对。
func checkFollowing(){
let url = URL(string: "xxx")
//request to this file
var request = URLRequest(url: url!)
//method to pass data
request.httpMethod = "POST"
//body to be appended to url
let body = "id=\(user?["id"] as! String)&follower_id=\(imageID)"
request.httpBody = body.data(using: String.Encoding.utf8) //multi language support
//launching
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
if error == nil{
//communicate back to UI
DispatchQueue.main.async(execute: {
do{
//get json result
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?
NSDictionary
//assign json to a new var parseJSON in guard secured way
guard let parseJSON = json else{
print("error while parsing")
return
}
if parseJSON["status"] as! String == "1"{
self.followBtn.setTitle("Following", for: .normal)
self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
} else if parseJSON["status"] as! String == "0"{
self.followBtn.setTitle("Follow", for: .normal)
}
} catch{
print("Caught an error: \(error)")
}
})
//if unable to proceed with request
} else{
print("error: \(error)")
}
//launch prepared session
}).resume()
}
答案 0 :(得分:0)
通过控制器上的变量跟踪其状态将是更好的方法。
bionmial()
(取决于您是否要将其设为可选,隐式展开的可选项,或设置默认值,但当然如果您使用常规可选项,则需要为最后一部分打开它<) / p>