在循环Swift 4中执行POST请求

时间:2018-03-07 01:08:23

标签: ios swift urlrequest urlsession

我想向我所拥有的Web服务器发出多个POST请求,这些请求会在我的数据库的表中插入新记录。这将根据用户输入的练习量重复进行。

我有POST请求的功能,如下所示。

    func submitDetails(split_id:Int, day:String, name:String, set:String, rep:String)
{
    var request = URLRequest(url: URL(string: "LINK OF WEB SERVICE")! as URL)
    request.httpMethod = "POST"
    let postString = "id=\(split_id)&day=\(day)&name=\(name)&sets=\(set)&reps=\(rep)"
    print("Post string - \(postString)")
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest)
    {
        data, response, error in

        if error != nil
        {
            print("error=\(String(describing: error))")
            return
        }

        print("response = \(String(describing: response))")

        let responseString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        print ("responseString =\(String(describing: responseString))")
    }
    task.resume()
}

这是在循环中调用的,

for x in 0...MainMenuViewController.myVariables.day1NoExercise - 1
            {
                self.submitDetails(split_id: MainMenuViewController.myVariables.new_split_id, day: self.dayName.text!, name: self.exerciseName[x].text!, set: self.exerciseSets[x].text!, rep: self.exerciseReps[x].text!)
            }

目前,用户输入数据的第一个练习被插入到数据库中。好像它正在执行所有代码太快。我希望有人理解这一点,并能帮助我!

1 个答案:

答案 0 :(得分:1)

  • for API Calls始终运行异步请求
  • 使用后台线程来帮助您的应用程序保持响应
  • 使用编译块显示错误
  • 显示进度条或类似内容,让用户知道您正在做某事
  • 为您的服务器添加额外功能,以允许批量发布“减少http会话”

阅读: https://medium.com/@sdrzn/networking-and-persistence-with-json-in-swift-4-c400ecab402d https://medium.com/@sdrzn/networking-and-persistence-with-json-in-swift-4-part-2-e4f35a606141

  • 建议: 看起来你正在使用Swift / IOS迈出第一步所以只需使用像Alamofire这样的http库来避免像排队,线程,Complitions Block这样的头疼。

https://github.com/Alamofire/Alamofire