在尝试链接xcode8上生成的woo-commerce api时,我收到错误401(谷歌上有点发现它的身份验证错误)但是相同的api链接和键似乎在浏览器上正常工作。添加xcode的代码片段以供参考。
let urlString = "https://serverUrl.com"
func downloadJsonWithURl(){
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(url: url as! URL)
//keys for authentication
request.addValue("A KEY", forHTTPHeaderField: "Consumer-key")
request.addValue("A SECRET", forHTTPHeaderField: "Secret-key")
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
print (jsonObj as Any)
}
}) .resume()
}
稍微戳了一下。我解决了这个问题。只需修改.plist文件即可添加App Transport Security设置,并允许在Web内容中允许任意加载并允许任意加载为YES。