iOS Swift停止重复的HTTP请求

时间:2019-05-05 15:22:51

标签: ios swift

我是Swift的新手,正在使用Swift4。我有一个动作,当点击按钮时会发送HTTP请求。在后端,它将一条记录插入数据库。所有这些都可以正常运行,但是有时即使我一旦Swift两次发送HTTP请求两次便点击了按钮,然后我又得到了重复的记录。有办法阻止这种情况吗?这是我的简单代码

@IBAction func submitAction(_ sender: Any) {

    let url:URL = URL(string:ConnectionString+"insert_location")!
    var myName = ""
    TableSource.isHidden = true
    let session = URLSession.shared
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    if let fullname = UserDefaults.standard.string(forKey: "fullname") {
        myName = fullname
    } else {
        myName = "UnKnown"
    }
    let address = "Unknown"

    let location = Location[0]
    let parameter = "location=\(location)&latitude=\(latitude!)&longitude=\(longitude!)&name=\(namePlaceStreet.text!)&address=\(address)&profile_id=\(MYID)&fullname=\(myName)"
    request.httpBody = parameter.data(using: String.Encoding.utf8)
    session.dataTask(with:request, completionHandler: {(data, response, error) in
        if error != nil {

        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                if let Streams = parsedData["result"] as? [AnyObject] {
                    DispatchQueue.main.async {
                        for Stream in Streams {
                            if let notification = Stream["outcome"] as? String {
                                self.coordinates.isHidden = false
                                self.coordinates.text = String(notification)
                                self.submitButton.isHidden = true
                                self.namePlaceStreet.isHidden = true
                                self.topLabel.isHidden = true
                            }
                        }
                    }
                }
            } catch let error as NSError {
                print(error)
            }
        }
    }).resume()
}

1 个答案:

答案 0 :(得分:1)

此代码是异步代码,因此最好在操作开始时添加活动指示器,并在成功/错误时将其删除,或者禁用按钮

@IBAction func submitAction(_ sender: UIButton) {

   guard sender.isEnabled else { return } // in case for a messy outlet connection

   sender.isEnabled = false 

   .....

    DispatchQueue.main.async {
      sender.isEnabled = true
    }
}

多次单击它是预期的用户体验,因此您需要对其进行处理