gpt4 book ai didi

ruby-on-rails - Rails JSON 到 Swift 2 JSON

转载 作者:行者123 更新时间:2023-11-30 14:15:51 24 4
gpt4 key购买 nike

我正在尝试使用 JSON 将数据从 Rails Web 服务器共享到 swift 应用程序。我正在努力建立这种联系。

从 Rails Controller :

    ...
output = x.to_json
render :json => output
...

在 Swift iOS 应用程序中:

import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
reachForWebsite()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func reachForWebsite(){
let url = NSURL(string: "myURL")
let request = NSURLRequest(URL: url!)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data!, encoding: NSUTF8StringEncoding))
var error: NSError? = nil
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error = &error){
if let dict = jsonObject as? NSDictionary {
println(dict)
} else {
println("not a dictionary")
}
} else {
println("Could not parse JSON: \(error!)")
}
println(data.dynamicType)
}
}
task!.resume()
}
}

我可以验证我是否成功接收数据,因为我可以将其转换为字符串并将其打印到应用程序上的控制台。但是我无法从中创建 NSDictionary 对象。错误随着每个修补程序的不同而变化,但与Options和try catch相关。

JSON

{"inside":[{"name":"BOB"}, ...],"outside":[{"name":"TIM","type":"HUMAN","id":1}, ...],"info":{"time":"2015-07-02"}}

最佳答案

为什么不尝试用 Swift 2 解析 JSON

guard let task = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
guard let data = data, error == nil
else
{
// Checks for errors if the task fails like for bad connectivity.
print(error);
return;
}
do
{
guard let JSONDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject]
else
{
// The JSONDict wasn't a dictionary. Maybe its an array here? If it is change the structure of the parsing.
print("The JSON wasn't a dictionary. Try array by optional casting to [AnyObject] instead of the cast above to [NSObject: AnyObject]")
return
}
print("Parsed JSON successfully as dictionary: \(JSONDict)")
// Do stuff with the JSONDict which is a Swift dictionary.
// For example: let some = JSONDict["key"] as? ValueType will allow you to access the key of the JSONDict
}
catch
{
// JSON parsing error.
print(error)
}
else
{
// Error task wasn't created that's unusual unless the URL was bad.
// Fail here so that you can trace the stack and debug.
assertionFailure();
}
task.resume()

如果它不起作用,请告诉我哪里失败以及控制台会打印什么内容。

关于ruby-on-rails - Rails JSON 到 Swift 2 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com