ios - Swift:Web 服务 API 调用在某些网络上返回错误

标签 ios json swift nsurl

我正在使用 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/

相关文章:

iphone - 向 MKMapView 添加 subview (不是叠加层)

php - 在 JSON 请求中没有来自服务器的响应

ios - swift ,将单选按钮组添加到 TableView 单元格

php - 结合 ios (Push notification) 和 android (GCM) API (webservice) 进行通知

javascript - Json,获取另一个级别内的信息

arrays - 在字典的数组中加载带有字典的 JSON 文件

java - HashMap 中的 Jackson 日期格式

swift - 安全文本 .echosbullets 不适用于密码字段

swift - 如何修复 : gradient background at landscaping?

ios - Swift 3. 尝试从 viewController 更新原型(prototype)单元类中声明的一些 IBOutlet