我正在构建移动应用程序以使用基于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
}
我发布此帖后,通过阅读django
在jsonObject
中创建必要的模型。
响应无关紧要,因为我通过FCM
通知其他用户可能需要很长时间。
这就是我要做的事情:
我该如何实现这个目标?
答案 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
}
}