如何将json请求发送到服务器而不是等待响应

时间:2016-08-17 18:45:45

标签: django swift http post

我正在构建移动应用程序以使用基于django的后端。我在swift中发布了这样的帖子请求:

 var request: NSMutableURLRequest = NSMutableURLRequest()
        var url = "https://webapp.com/makepost/"
        url += NSUserDefaults.standardUserDefaults().stringForKey("userPk")!
        url += "/"

        var err: NSError?

        request.URL = NSURL(string: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData




        request.setValue("application/json", forHTTPHeaderField: "Content-Type")


        do {

            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(JSONObject, options:  NSJSONWritingOptions(rawValue:0))
        } catch _ {
            print ("error")

        }







 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {(response, data, error) -> Void in


            var query = String(data: data!, encoding: NSUTF8StringEncoding)


            query = query!.stringByReplacingOccurrencesOfString("Optional(", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
            query = query!.stringByReplacingOccurrencesOfString(")", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
            print(query)
            //update ui




        }

我发布此帖后,通过阅读djangojsonObject中创建必要的模型。

响应无关紧要,因为我通过FCM通知其他用户可能需要很长时间。

这就是我要做的事情:

  1. 发帖请求。
  2. 忽略回复。
  3. 在发布帖子请求后立即更新用户界面。
  4. 我该如何实现这个目标?

1 个答案:

答案 0 :(得分:-1)

喜欢这样

 //set request variable here
 let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
 dispatch_async(dispatch_get_global_queue(priority, 0)) {


            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {(response, data, error) -> Void in


                var query = String(data: data!, encoding: NSUTF8StringEncoding)







            }
            sleep(2)
            // wait two seconds for models to create in backend


            dispatch_async(dispatch_get_main_queue()) {

                self.refresh(self.refreshButton)
                //refresh ui here with method that fires another get request




            }
        }