我正在使用 Swift 创建一个 iOS 应用程序,它使用一些 Web 服务来获取一些信息。具体来说,我正在使用 food2fork API 来获取一些食谱。我遇到的问题是,如果我在大学连接到互联网,网络调用将始终返回错误,即使我知道我已通过电话连接到互联网。我认为该错误与网络如何处理安全网站有关,但我不确定。
我没有正确使用 NSURL 吗?有没有更好的方法可以确保我的网络调用始终返回应用程序所需的数据?这是函数:
func getRecipeByID(recipeId: String, sendTo: RecipeInfoViewController)
{
let theURLAsString = "http://food2fork.com/api/get?key=[MY KEY]&rId=" + recipeId
let theURL = NSURL(string: theURLAsString)
let theURLSession = NSURLSession.sharedSession()
let theJSONQuery = theURLSession.dataTaskWithURL(theURL!, completionHandler: {data, response, error -> Void in
if(error != nil)
{
print(error!)
}
do
{
let theJSONResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if theJSONResult.count > 0
{
let theRecipeDictionary = theJSONResult["recipe"] as? NSDictionary
sendTo.setRecipeInfo(theRecipeDictionary!)
}
} catch let error as NSError {
print(error) //The function always gets here on certain networks
}
})
theJSONQuery.resume()
}
在 print(error) 行输出的错误是:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
最佳答案
如果您运行的是 iOS 9,则需要禁用 App Transport Security通过将 key 添加到您的 Info.plist 来获取该域。否则,您将无法建立非 HTTPS 连接。
关于ios - Swift:Web 服务 API 调用在某些网络上返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010489/