为什么没有打印任何结果?
我一直在寻找答案。我尝试了许多不同的示例代码块。除非产生错误,否则打印语句永远不会触发。例如:如果我仅将 URL 更改为“http”,而没有其他任何内容,我自然会收到错误并打印该错误。但是,任何有效的 URL 都不会在 print 语句中产生结果。
func post()
{
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thebeerstore.ca")!)
request.HTTPMethod = "POST"
let postString = "experiment"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString!)")
}
task.resume()
}
编辑:如果我使用 Playground ,它就可以工作,但只能在 Playground 中。
最佳答案
在应用程序的 Info.plist 文件中,添加属性 App Transport Security Settings
,并在其下添加 Allow Arbitrary Loads
并分配 YES
为了它。
通过 Info.plist 中的上述设置,应用程序应该也能够加载您的 http://
网址
Note: I would recommend not to use the above settings in your production build, it could result in security issues.
关于ios - NSURLSession.sharedSession().dataTaskWithRequest(request) 除非出现错误,否则不会返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34004425/