【问题标题】:Populate UItableview with parse and url使用 parse 和 url 填充 UItableview
【发布时间】:2016-01-20 23:35:56
【问题描述】:

什么是从 URL 填充 tableview 的最佳实践,该 URL 从 URL 字符串中解析用户数据。当前代码正在运行,但如果在运行 URL 请求之前未加载解析用户数据,则可能会导致错误。这将导致表格无法加载(不是安全代码)

解析中的用户类有一个“teamNumber”键,它插入到 URL 中以获取页面源的字符串。从那里处理字符串以创建一个显示为表格视图的数组。

这里是代码(编辑去掉字符串操作):

override func viewDidLoad() {
    super.viewDidLoad()

    //To the internet to grab the "leagueNumber" of a user to input into the attemptedUrl string
    let leagueNumber = PFUser.currentUser()!["leagueNumber"] as? String

    //Plug in the league number from parse into URL string
    let attemptedUrl = NSURL(string: "http://someURL.leagueapps.com/leagues/\(leagueNumber!)/teams")

    if let url = attemptedUrl {

        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

            if let urlContent = data {

                let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)

                //Manipulate string to get the team information
                //Ends up with array [team1, team2, team3, team4] to populate the tableview

                }

            } else {

                print("URL could not connect")

            }

            //Close internet session
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.tableView.reloadData()

            })
        }

        task.resume()

    } else {

        print("Fail")

    }
}

有没有更安全的方法来实现这段代码?

【问题讨论】:

    标签: ios xcode swift uitableview parse-platform


    【解决方案1】:

    我想您可以通过使用查询从解析中获取完整的用户对象,然后使用该结果形成您的 URL,从而使其“更安全”:

    var query = PFUser.query
    var currentUser = PFUser.currentUser()
    query.whereKey("username", equalTo: currentUser.username)
    query.getFirstObjectInBackgroundWithBlock {
      (object: PFObject?, error: NSError?) -> Void in
      if error != nil || object == nil {
        println("The getFirstObject request failed.")
      } else {
        // The find succeeded.
                leagueNumber = object["leagueNumber"] as! String!
    
        println("Successfully retrieved the object.")
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      相关资源
      最近更新 更多