0
我有一個選擇的形式返回數據的Web服務:如何從我的JSON中使用SwiftyJSON獲取選定元素並將其打印在控制檯上?
[{"_id":"56c861d0bcb42e075f7d47bd",
"username":"Shaylee Thompson",
"photo":"photo.jpg",
"number":"one",
"description":"Aut officia et ipsam. Dolorem pariatur molestiae sed saepe voluptatem voluptatem. Non maiores doloribus quis eum reprehenderit fugit vitae.",
"__v":0,
"updated_at":"2016-02-20T12:53:36.931Z",
"created_at":"2016-02-20T12:53:36.922Z",
"location":{
"type":"Point",
"coordinates":[-3.2880974020993934,49.8319259687921]}
},
{"_id":"55a9253297b21080ac8",
"username":"Eve Notter",
"photo":"photo.jpg",
"number":"two",
"description":"Aut officia et ipsam. Dolorem pariatur molestiae sed saepe voluptatem voluptatem. Non maiores doloribus quis eum reprehenderit fugit vitae.",
"__v":0,
"updated_at":"2016-02-20T12:53:36.931Z",
"created_at":"2016-02-20T12:53:36.922Z",
"location":{
"type":"Point",
"coordinates":[-2.212142,41.14321231]}
},
etc.
,我想在我的控制檯location
,username
和description
從每個記錄上面顯示。
我創建了一個名爲RestManager.swift
類,它包含兩個方法:
static let sharedInstance = RestApiManager()
func getRandomUser(onCompletion: (JSON) -> Void) {
let route = baseURL
makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as 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 -> Void in
let json:JSON = JSON(data: data!)
onCompletion(json, error)
// if I put print(json) then I see the whole json in console
})
task.resume()
}
,然後在不同的I類寫道:
override func viewDidLoad() {
getDummyData()
}
func getDummyData() {
RestApiManager.sharedInstance.getRandomUser { json in
let results = json["username"]
for (index: String, subJson: JSON) in results {
let user: AnyObject = JSON["username"].object
dispatch_async(dispatch_get_main_queue(),{
print(user) //does not print anything so far
})
}
}
}
所以我的問題是 - 我應該如何修改我的getDummyData
方法,以便我可以在控制檯中看到我的JSON元素?