2015-07-02 24 views
0

我想從我的Rails Web服務器共享數據到一個具有JSON的Swift應用程序。我正在努力做到這一點。Rails的JSON到Swift 2 JSON

從Rails的控制器:

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

在斯威夫特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對象。這些錯誤隨每個修補程序而改變,但涉及到可選項並嘗試捕獲。

JSON

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

你可以發佈一個你正在解析的JSON的例子嗎? –

+0

這聽起來像你的JSON格式有問題,或者它可能是一個數組而不是字典?此外,這可能或不是你正在尋找的答案的一部分,但這是一個愉快的機會,用開關盒打開optionals:https://gist.github.com/patricklynch/8d5b792c5fa2aad95fe7 –

+0

@PatrickLynch更新的問題與JSON格式 – Marcus

回答

0

你爲什麼不嘗試用這種斯威夫特2

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() 

解析JSON如果它不工作,告訴我在哪裏失敗,什麼獲取打印到控制檯。