2016-08-17 86 views
0

我正在構建移動應用程序,以我的django爲基礎的後端。我使swift POST請求是這樣的:如何發送json請求到服務器,而不是等待響應

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 




     } 

只要我做這個職位它創造了必要的模型django通過閱讀jsonObject

響應無關緊要,並且可能需要很長時間才能通過FCM通知其他用戶。

這就是我想要做的事:

  1. 做一個POST請求。
  2. 忽略響應。
  3. 在發出發佈請求後立即更新UI。

我該怎麼做到這一點?

回答

-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 




      } 
     } 
相關問題