Swift:使用Alamofire处理JSON& SwiftyJSON [英] Swift: Handling JSON with Alamofire & SwiftyJSON

查看:115
本文介绍了Swift:使用Alamofire处理JSON& SwiftyJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这肯定会被问到好几次,但我还没有找到正确的答案,尽管我一直很努力。

This is sure to be asked several times, but I have not yet found the right answer, although I have been looking very hard.

我使用Alamofire和SwiftyJSON,我的JSON数据看起来像这样:

I use Alamofire and SwiftyJSON and my JSON data looks like that:

{
  "528" : {
    "name" : "Name 1",
    "id" : "528",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "29" : {
    "name" : "Name 2",
    "id" : "29",
    "product_id" : null,
    "visible" : "1",
    "level" : "1"
  },
  "173" : {
    "name" : "Name 3",
    "id" : "173",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "143" : {
    "name" : "Name 4",
    "id" : "143",
    "product_id" : null,
    "visible" : "1",
    "level" : "2"
  },

...使用此代码:

Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)

    .responseJSON { (request, response, jsonData, error) in

        let json = JSON(jsonData!) 

        println(json)

    }

...所以一切都应该没问题JSON

...so everything should be fine with JSON


  1. 我如何访问这些数据?我的意思是如何获取名称,ID,product_ids等

  1. How can i access to that data? I mean how can i get names, ids, product_ids etc

如何将该数据(名称)放入我的TableViewController?

How can i put that data (name) to my TableViewController?


推荐答案

我在我的一个项目中使用SwiftyJSON和Alamofire。以下是我使用它的方法。

I am using both SwiftyJSON and Alamofire in one of my projects. Here is how I am using it.


  1. 创建一个名为APIProtocol的协议。

  2. 设置API接受类型为APIProtocol的委托的GET方法的类。

  3. 设置TableViewController以实现APIProtocol。

  4. 从TableViewController调用API.get()

  1. Create a protocol called APIProtocol.
  2. Setup an API class with a GET method that accepts a delegate of type APIProtocol.
  3. Setup TableViewController to implement the APIProtocol.
  4. Call API.get() from TableViewController



代码



Code

// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET, url, parameters: parameters)
    .responseJSON { (req, res, json, error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String, activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,
        message: activity["message"].stringValue
      )

      activities.addObject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread, and update the UI.
    dispatch_sync(dispatch_get_main_queue(), {
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities", delegate: self)
}

这篇关于Swift:使用Alamofire处理JSON& SwiftyJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆