ios – Swift:使用Alamofire和SwiftyJSON处理JSON

前端之家收集整理的这篇文章主要介绍了ios – Swift:使用Alamofire和SwiftyJSON处理JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这肯定会被问过几次,但我还没有找到正确的答案,尽管我一直很努力.

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

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

…使用此代码

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

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

        let json = JSON(jsonData!) 

        println(json)

    }

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

>我如何访问该数据?我的意思是我如何获得名称,ID,product_ids等
>我如何将该数据(名称)放入我的TableViewController?

解决方法

我在我的一个项目中使用了SwiftyJSON和Alamofire.这是我如何使用它.

>创建一个名为APIProtocol的协议.
>使用GET方法设置API类,该方法接受APIProtocol类型的委托.
>设置TableViewController以实现APIProtocol.
>从TableViewController调用API.get()

// 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)
}
原文链接:https://www.f2er.com/iOS/332855.html

猜你在找的iOS相关文章