私は Swift と JSON を初めて使用するので、これがばかげている場合はご容赦ください。この特定の JSON http://jsonplaceholder.typicode.com/usersを迅速に解析しようとしています。http://jsonplaceholder.typicode.com/users/1と入力して 1 人のユーザーの値を取得できますが、一度に1 人のユーザーの値しか提供されないという問題があります。すべてのユーザーの値を一度に取得する方法を探しています。
SwiftyJSON API を使用しています。
これは私が使用しているコードです:
// RestApiManager.swift
import Foundation
typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject{
static let sharedInstance = RestApiManager()
let baseURL = "http://jsonplaceholder.typicode.com/users/"
func getUser(onCompletion: (JSON) ->Void){
makeHTTPGetRequest(baseURL, onCompletion: {json, err -> Void in onCompletion(json)})
}
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse){
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
let json:JSON = JSON(data: data)
onCompletion(json, error)
})
task.resume()
}
}
これは私の MasterViewController.swift クラスです
//
// MasterViewController.swift
//
//
import UIKit
class MasterViewController: UITableViewController {
var objects = [AnyObject]()
var contactsData = NSMutableArray() //array that will hold all the contact details.
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
RestApiManager.sharedInstance.getUser { json -> Void in
let user: AnyObject = json["id"].object
self.contactsData.addObject(user)
println(self.contactsData)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contactsData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as? UITableViewCell
return cell
}
}