【发布时间】:2016-03-04 18:58:22
【问题描述】:
我正在使用 Swift 创建一个 iOS 应用程序,它使用一些网络服务来获取一些信息。具体来说,我正在使用 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 文本没有开始 带有数组或对象以及允许未设置片段的选项。” UserInfo={NSDebugDescription=JSON 文本不是以数组开头或 允许未设置片段的对象和选项。}
【问题讨论】:
-
我认为您的大学可能出于某种原因阻止了
food2fork网站。您是否检查了返回的data作为字符串? -
它还阻止了我尝试与它一起使用的其他 Web 服务。所有似乎都是 HTTP 调用而不是 HTTPS,这可能是原因吗?