swift xml rss reader ...让它异步

时间:2014-10-30 16:20:07

标签: swift asynchronous

您好我正在努力进行一项简单的练习。我做了这个基本的xml rss阅读器,它工作正常,但我很乐意改进它并担心异步加载。我应该怎么做?

import UIKit

class ViewController: UITableViewController, NSXMLParserDelegate, UITableViewDelegate {



    let urlstring = "http://www.nasa.gov/rss/dyn/breaking_news.rss"
    var element:NSString = ""
    var items:[String] = []
    var item = ""


    override func viewDidLoad() {
        super.viewDidLoad()

     //   dispatch_queue_t myQueue = dispatch_queue_create("queue",NULL)

        loadParser()
    }

    //MARK - tableviewdelegate

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel.text = items[indexPath.row]

        return cell
    }

    //MARK - parser

    func loadParser(){
        let url = NSURL(string: urlstring)
        var parser = NSXMLParser(contentsOfURL: url)
        parser?.delegate = self
        parser?.shouldProcessNamespaces = true
        parser?.shouldReportNamespacePrefixes = true
        parser?.shouldResolveExternalEntities = true
        parser?.parse()
    }



    //MARK: - Parser Delegate

    func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {

        element = elementName
        if ((elementName as NSString).isEqualToString("item")){
            item = ""
        }

    }


    func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {

        if ((elementName as NSString).isEqualToString("item")){
            items.append(item)
        }
    }


    func parser(parser: NSXMLParser!, foundCharacters string: String!) {
        if ( (element.isEqualToString("title")) && (element != "") ){
            item += string
        }
    }



    func parserDidEndDocument(parser: NSXMLParser!) {
        println(items)
        self.tableView.reloadData()
    }


}

我不知道该怎么做。我试图将“loadParser”包装在一个调度队列中,但是在swift中它不起作用。你们能告诉我如何使用GCD吗?感谢

2 个答案:

答案 0 :(得分:1)

对于仍在寻找解决方案的所有人来说,这里使用的代码非常适合我使用此代码SWXMLHash

要使此代码正常工作,您必须使用SWXMLHash使XML解析异步的最佳方法

  

使用Swift 2.0解决此问题

//  test.swift
//  Test Ground
//
//  Created by O-mkar on 14/12/15.
//  Copyright © 2015 Test Ground. All rights reserved.
//

import UIKit
import SWXMLHash //import SWXML Class

class test: UITableViewController { //Change this test to your name



    let urlstring = "http://www.nasa.gov/rss/dyn/breaking_news.rss"
    var items:[String] = []


    override func viewDidLoad() {
        super.viewDidLoad()


        loadParser()
    }


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel!.text = items[indexPath.row]

        return cell
    }

    //MARK - parser

    func loadParser(){

        let request = NSMutableURLRequest(URL: NSURL(string: urlstring)!)
        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "GET"

        var err: NSError?

        let task = session.dataTaskWithRequest(request) {
            (data, response, error) in

            if data == nil {
                print("dataTaskWithRequest error: \(error)")
                return
            }

            func pars(){
                let xml = SWXMLHash.parse(data!)

                for elem in xml["rss"]["channel"]["item"] {

                    self.items.append((elem["title"].element?.text)!)

                }

               //reload data after fetch
                self.tableView.reloadData()


            }
           //sending async task
            dispatch_async(dispatch_get_main_queue(), pars)


        }
        task.resume()

    }


}
  

输出

OUTPUT

  

我用来制作ASYNC的代码

 let request = NSMutableURLRequest(URL: NSURL(string: urlstring)!)
        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "GET"

        var err: NSError?

        let task = session.dataTaskWithRequest(request) {
            (data, response, error) in

            if data == nil {
                print("dataTaskWithRequest error: \(error)")
                return
            }

            func pars(){
                let xml = SWXMLHash.parse(data!)

                for elem in xml["rss"]["channel"]["item"] {

                    self.items.append((elem["title"].element?.text)!)

                }

               //reload data after fetch
                self.tableView.reloadData()


            }
           //sending async task
            dispatch_async(dispatch_get_main_queue(), pars)


        }
        task.resume()

答案 1 :(得分:0)

怎么样:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    loadParser();
});

这应该与原始的Objective-C解决方案相同