10

これは何度か聞かれると思いますが、一生懸命探してもまだ正解にたどり着けていません。

Alamofire と SwiftyJSON を使用しており、JSON データは次のようになります。

{
  "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 で問題ないはずです

  1. どうすればそのデータにアクセスできますか? 名前、ID、product_ids などを取得する方法を教えてください。

  2. そのデータ(名前)をTableViewControllerに入れるにはどうすればよいですか?

4

6 に答える 6

16

プロジェクトの 1 つで SwiftyJSON と Alamofire の両方を使用しています。これが私がそれを使用している方法です。

  1. APIProtocol というプロトコルを作成します。
  2. タイプ APIProtocol のデリゲートを受け入れる GET メソッドを使用して API クラスをセットアップします。
  3. APIProtocol を実装するように TableViewController をセットアップします。
  4. 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)
}
于 2014-11-02T02:47:28.503 に答える
4

アクセサー (少なくとも SwiftyJSON の場合) は次のように機能します。

if let userName = json[0]["528"]["name"].string{
    println(userName) // "Name 1"
}

SwiftyJSOn の使用方法の詳細については、公式ドキュメントhttps://github.com/SwiftyJSON/SwiftyJSONを参照してください。

そのデータをUITableViewに入れる方法に関しては、多くの方法があります。UITableView セルを設定し、JSON データを何らかの配列にロードします。

于 2014-11-01T03:02:06.013 に答える
1

コードでAlamofireを使用する方法と、JSON応答を迅速かつ解析してモデルを作成する方法を宣言する例については、このリポジトリを確認してください

  1. プロジェクトに Alamofire をインストールする
  2. クラスに Alamofire をインポートする
  3. クラスでこれらの変数を定義します

    typealias complitionBlock = (data: AnyObject) -> Void
    
    let KBASE_URL: String = "http://static.westwing.de/cms/dont-delete/programming_task/data.json"
    
  4. この関数の実装を設定します

    func getMainItems(complition block: complitionBlock) {
    
    Alamofire.request(.GET, KBASE_URL, parameters:nil).responseJSON { response in
    
         do {
            let items = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions()) as! NSArray
    
             let mutableArray: NSMutableArray = []
    
             items.enumerateObjectsUsingBlock({ object, index, stop in
                 let str = object as! NSDictionary
                 //Replace WESItem with your model
                 //let item = WESItem(dictionary: str as NSDictionary)
                 mutableArray.addObject(item)
             })
             block(data: mutableArray)
         } catch {
             print(error)
         }
     }
    }
    

詳細情報: https://github.com/AhmedAskar/WestWing

于 2016-07-29T11:18:22.993 に答える
0

以下はあなたのために働くはずです:-

           var nameArr = [String]() 

            Alamofire.request(.GET,"your url", parameters: nil)
                      .validate().responseJSON { response in
                         if let responseJson = response.result.value {
                           let name = responseJson["name"] as! String
                           nameArr.append(name)
                          }

                            dispatch_async(dispatch_get_main_queue(), {
                            self.tableView.reloadData()
                            })
                     }// Alamofire Close




 Use tableview as you normally use it i.e.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")

        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }

        cell!.textLabel?.text = nameArr[indexPath.row]
        return cell!
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArr.count
    }

注: Alamofire は「.responseJSON」内で直接処理できる JSON 応答を許可するため、Swifty JSON を使用する必要はありません。

于 2016-07-26T04:54:39.303 に答える