JSON을 구문 분석하기 위해 Swift2에서 자체 함수를 작성했습니다. JSON이 구문 분석되면 JSON에서 가져온 데이터 목록이 tableView
내 앱에 표시됩니다 . 이 데이터를 알파벳 순서로 표시하는 방법을 알아 내려고합니다. 나는 이것이 내가 함수에서 호출하는 append 메소드 전에 어딘가에서 일어날 필요가 있다고 생각합니다. 나는 이것이 sort
함수 가 될 필요가 있다고 생각 하지만 Swift2에서 이것을 제대로 실행할 올바른 정렬 함수를 알아낼 수 없었습니다. 도움을 주시면 감사하겠습니다! 내 parseJSON 함수는 다음과 같습니다.
func parseJSON(){
do{
let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
for anItem in jsonResult as! [Dictionary<String, AnyObject>]{
let mifiName2 = anItem["name"] as! String
let mifiId = anItem["employeeId"] as! Int
let newName = Name(mifiName: mifiName2, mifiId: mifiId)
nameOfMifi.append(newName)
//print("Name: \(newName)")
}
}
catch let error as NSError{
print(error.debugDescription)
}
}
sort
모든 객체가 루프 후에 의미 가 append
있는 후에 배열 이 필요합니다 .Array
for
for anItem in jsonResult as! [Dictionary<String, AnyObject>]{
let mifiName2 = anItem["name"] as! String
let mifiId = anItem["employeeId"] as! Int
let newName = Name(mifiName: mifiName2, mifiId: mifiId)
nameOfMifi.append(newName)
//print("Name: \(newName)")
}
//Now you need to sort your array on the basis of name like this
nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName }
편집 : @vadian이 제안했듯이 NSData(contentsOfURL:)
UI를 차단하므로 사용하지 마십시오 NSURLSession
.
let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!
var task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) -> Void in
if error != nil {
return
}
if let jsonResult = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [Dictionary<String, AnyObject>] {
for anItem in jsonResult {
let mifiName2 = anItem["name"] as! String
let mifiId = anItem["employeeId"] as! Int
let newName = Name(mifiName: mifiName2, mifiId: mifiId)
nameOfMifi.append(newName)
//print("Name: \(newName)")
}
//Now you need to sort your array on the basis of name like this
nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName }
//Now reload tableView on main thread.
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
})
task.resume()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다