2016-11-22 43 views
1

我在Swift2中編寫了自己的函數來解析JSON。解析JSON後,從我的應用程序中的tableView中顯示從JSON中提取的數據列表。我試圖弄清楚如何按字母順序顯示這些數據。我認爲這需要在函數中調用的append方法之前發生。我想這應該是一個sort函數,但我一直無法弄清Swift2中正確的排序函數,它會正確執行。任何幫助,我可以得到讚賞! 這裏是我的parseJSON功能:swift:從JSON中解析Alphabetiz數據

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) 
    } 
} 
+2

** **從來沒有從與同步法服務器負載數據'NSData的(contentsOfURL:'和'MutableContainers'是沒用的斯威夫特 – vadian

回答

1

您需要sort陣列後所有的對象是appendArrayfor循環之後手段。

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:),因爲它會阻止你的用戶界面,讓麪糊用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() 
+0

請檢查一次編輯答案:) –

+0

在哪裏呢的方法。重新加載tableView去?我試圖把它放在我的viewDidLoad(),我不斷收到錯誤:「模糊引用成員'tableView'」在世界上自我 – user7077886

+0

@ user7077886檢查編輯答案,在這裏'self.tableView'是你的tableView插座,你已創建,您需要使用tableView Outlet名稱進行更改。 –