繁体   English   中英

用解析和URL填充UItableview

[英]Populate UItableview with parse and url

从URL填充表视图的最佳实践是什么,该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")

    }
}

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

我以为您可以通过从查询解析中获取完整的用户对象,然后以该结果形成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.")
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM