如何从两个URL解析两个XML文件(Swift)

时间:2016-05-05 02:25:57

标签: ios xml swift

我有两个XML网址。第一个网址在SongName上显示Table,第二个网址显示SongPath。当我点击表格上的SongName时,它会转到第二个网址中的SongPath。这是 table。您可以在代码中看到SongName网址。

这是XML:

<NewDataSet>
  <Table>
    <SongName>AYA LIV LIVOKIM PEL?STANKTV</SongName>
  </Table>
  <Table>
    <SongName>DîLAN PPP PELISTANK</SongName>
  </Table>
  <Table>
    <SongName>KARIN BAL DAGRIM</SongName>
  </Table>
  <Table>
    <SongName>RUKEN WERE CANE</SongName>
  </Table>
</NewDataSet>

这是SongPath的第二个网址:

这就是XML:

<NewDataSet>
  <Table>
    <SongPath>http://jo.sms2tv.com/PelistankApp/Songs/song1.mp3</SongPath>
  </Table>
  <Table>
    <SongPath>http://jo.sms2tv.com/PelistankApp/Songs/song2.mp3</SongPath>
  </Table>
  <Table>
    <SongPath>http://jo.sms2tv.com/PelistankApp/Songs/song3.mp3</SongPath>
  </Table>
  <Table>
    <SongPath>http://jo.sms2tv.com/PelistankApp/Songs/song4.mp3</SongPath>
  </Table>
</NewDataSet>

这是我的Swift代码:

class ViewController: UIViewController, NSXMLParserDelegate, UITableViewDataSource, UITableViewDelegate
{

    @IBOutlet var tbData : UITableView?

    var parser = NSXMLParser()
    var posts = NSMutableArray()
    var elements = NSMutableDictionary()
    var element = NSString()
    var title1 = NSMutableString()
    var date = NSMutableString()

    override func viewDidLoad()
    {
     // Do any additional setup after loading the view, typically from a nib.
        super.viewDidLoad()
        self.beginParsing()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func beginParsing()
    {

        posts = []
        parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://jo.sms2tv.com/PelistankApp/default.aspx"))!)!
        parser.delegate = self
        parser.parse()

        tbData?.reloadData()
    }


    //////////////////////////////////////XMLParser Methods

    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        if (elementName as NSString).isEqualToString("Table")
        {
            elements = NSMutableDictionary()
            elements = [:]
            title1 = NSMutableString()
            title1 = ""
            date = NSMutableString()
            date = ""
        }
    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if (elementName as NSString).isEqualToString("Table") {
            if !title1.isEqual(nil) {
                elements.setObject(title1, forKey: "title")
            }
            if !date.isEqual(nil) {
                elements.setObject(date, forKey: "date")
            }

            posts.addObject(elements)
        }
    }

    func parser(parser: NSXMLParser, foundCharacters string: String)
    {
        if element.isEqualToString("SongName") {
            title1.appendString(string)
        } else if element.isEqualToString("pubDate") {
            date.appendString(string)
        }
    }
  ///////////////////////////////////////////XMLParser Methods


    //////////////////////////////Tableview Methods
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")!

        if(cell.isEqual(NSNull)) {
            cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil) [0] as! UITableViewCell
        }

        cell.textLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
        cell.detailTextLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("date") as! NSString as String

        return cell as UITableViewCell
    }


  //////////////////////////////////////Tableview Methods


    /////// Table Action ( Cell clicked ) ///////

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        print("Row: \(row)")

    }

    /////// Table Action ( Cell clicked ) ///////


    @IBAction func Song(sender: UIButton) {

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("ViewSong")
        self.presentViewController(nextViewController, animated:true, completion:nil)

    }

   @IBAction func BackTableToHome(sender: UIBarButtonItem) {

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("Home")
        self.presentViewController(nextViewController, animated:true, completion:nil)
    }

    //////////Button SecandViewController ////
    @IBAction func SecondViewController(sender: AnyObject) {

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("ViewSong")
        self.presentViewController(nextViewController, animated:true, completion:nil)
    }
}

请提出任何建议。我可以制作MP3播放器没问题,我只是想要它,这样当我点击表格中的一个单元格时,它将播放第二个XML URL中同一行的歌曲。

1 个答案:

答案 0 :(得分:0)

首先解析您的两个API并将歌曲名称和歌曲URL存储在一个数组中。并且只要你想要一次又一次地解析它,就可以访问它。

  

这个答案是使用SWXMLHash

进行解析

您可以使用Alamofire发出HTTP请求

let xml = SWXMLHash.parse(data!)
       for elem in xml["NewDataSet"]["Table"] {

            print(elem["SongName"].element?.text) //PRINT SONG NAME 
        }

有关XML解析的更多信息,我已经answered

//这是你想要的

    /////// Table Action ( Cell clicked ) ///////

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        print("Row: \(row)")

        print(posts.objectAtIndex(indexPath.row).valueForKey("date") as! NSString as String) //Prints the song url

    }

这是项目链接 https://drive.google.com/file/d/0B2csGr9uKp1DN1VodkNndmtQR2c/view?usp=sharing