【问题标题】:swift: Alphabetiz data being parsed from a JSONswift:从 JSON 中解析 A​​lphabetiz 数据
【发布时间】:2017-04-05 16:10:19
【问题描述】:

我在 Swift2 中编写了自己的函数来解析 JSON。解析 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)
    }
}

【问题讨论】:

  • 从不使用同步方法NSData(contentsOfURL:MutableContainers从服务器加载数据在Swift中是没有用的。

标签: ios json swift sorting swift2


【解决方案1】:

你需要sort你的数组,因为Array中的所有对象都是append,意味着在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:),因为它会阻塞你的用户界面,所以像这样使用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()

【讨论】:

  • 重载tableView的方法去哪了?我试着把它放在我的 viewDidLoad() 中,但我不断收到错误:“对成员 'tableView' 的模糊引用”
  • @user7077886 检查编辑后的答案,这里self.tableView 是您创建的 tableView 插座,您需要使用您的 tableView 插座名称进行更改。
  • 非常感谢!而且我不知道我应该使用 NSURLSessions,所以也感谢你的解释!
  • @user7077886 欢迎朋友 :)
猜你喜欢
  • 2019-04-30
  • 2018-03-19
  • 2020-01-08
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 2016-09-09
  • 2021-03-27
  • 2021-07-25
相关资源
最近更新 更多