json - oAuth 使用 SwiftyJSON 读取结果?

标签 json api swift oauth swifty-json

我正在创建一个使用 API 的应用程序,为了举例,我们只说 Twitter API,因为它是大多数人都熟悉的,使用哪个 API 以及在哪里使用并不重要JSON 结果来自。

因此,使用非安全 API,我可以运行以下代码:

let urlPath = "http://mySimpleApi.com/results.js"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in

    if error != nil {
        // If there is an error in the web request, print it to the console
        println(error.localizedDescription)
    }

    var err: NSError?
    var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
    if err != nil {
        // If there is an error parsing JSON, print it to the console
        println("JSON Error \(err!.localizedDescription)")
    }

    let json = JSON(jsonResult)




    let userName:JSON = json["user"]["name"]
    let userNameString = userName.string!
    println(userNameString)



})
task.resume()

结果以JSON格式返回,上面的程序代码成功打印出结果用户名。也许我应该快速向您展示 JSON 的格式,这样您就知道您在看什么。

{
  "user" : 
  {
    "name": "Bob",
    "login": "bob2006",
    "password": "bobsEncryptedPassword",
  }  
}

因此,当运行以下代码时,我在控制台中返回的名称为“Bob”;正是我所期望的。

很明显这很简单,我这样做只是为了探索和试验 JSON 以及使其与我的应用程序一起工作的方法。

所以我的问题是当我想使用像 Twitter 这样的 oAuth API 时。如果我只是发送一个未经身份验证的请求,我会得到预期的结果:

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

现在我期望发生的事情是当我更改我的原始代码并放置给我这个错误的链接时我可以指定 let userName:JSON = json["errors"][0] 选择 errors 区域中的第一个项目。我只是假设这是一个数组,因为它使用方括号打开。当这不起作用时,我尝试了 let userName:JSON = json["errors"][0][message] 但这不起作用,我得到了同样的错误。该错误突出显示代码并说:

Thread 3: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0)

然后在控制台中返回:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

我如此关心这个不起作用的原因更多是为了理解为什么它不起作用所以我知道当我在实际情况下玩这个 - 显然从 twitter API 中获取错误消息可能没有非常大的实际应用。

最后,我只想说,当我确实通过浏览器发送经过身份验证的请求时,文件会被下载,但不会像我一直使用的其他 JSON 文件那样显示在浏览器上。这在将其应用于应用程序时是否有所不同,还是它的工作方式完全相同,我只需要像使用任何其他 JSON 格式一样使用它?

我知道这是一个很长的问题,但我想我已经包含了所有相关信息。

请耐心等待 - 我只是在学习,谢谢。

最佳答案

替换

let userName: JSON = json["user"]["name"]
let userNameString = userName.string!
println(userNameString)

let dic = json["errors"][0]
let code = dic["code"].int
println(code!)

let msg = dic["message"].string
println(msg!)

第二个例子。

关于json - oAuth 使用 SwiftyJSON 读取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29370356/

相关文章:

mysql - 将 mySQL Express Node 转为 Json

javascript - 单击时在 JSON 数组选项之间切换

php - 发送时事通讯的最有效方式

Android 4.3 设备驱动 API 匹配错误

ios - NSFileHandle updateatPath 如何更新文件而不是覆盖?

ios - Objective C 应用程序中的 “Swift Language Version” 错误

python - 在 pandas json 中添加一个更高一级的对象

c++ - Windows api,是用C还是C++写的?

ios - 无法推断通用参数 'T' Xcode 11 iOS 13

php - Json编码整个mysql结果集