Xml parser in Swift

Asked

Viewed 204 times

0

I downloaded a ready project of rss Reader, it comes title description and image. However I am trying to edit the same for my xml.

see the codes:

//
//  FeedTableViewController.swift
//  RSSReader
//
//  Created by Training on 23/12/14.
//  Copyright (c) 2014 Training. All rights reserved.
//

import UIKit

class FeedTableViewController: UITableViewController, MWFeedParserDelegate, SideBarDelegate {

var feedItems = [MWFeedItem]()
var sidebar = SideBar()
var savedFeeds = [Feed]()
var feedNames = [String]()

func request(urlString:String?){

    if urlString == nil{

        let url = NSURL(string: "http://feeds.nytimes.com/nyt/rss/Technology")
        let feedParser = MWFeedParser(feedURL: url)
        feedParser.delegate = self
        feedParser.parse()
    }else{

        let url = NSURL(string: urlString!)
        let feedParser = MWFeedParser(feedURL: url)
        feedParser.delegate = self
        feedParser.parse()
    }


}

func loadSavedFeeds (){
    savedFeeds = [Feed]()
    feedNames = [String]()

    feedNames.append("Add Feed")

    let moc = SwiftCoreDataHelper.managedObjectContext()

    let results = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Feed), withPredicate: nil, managedObjectContext: moc)

    if results.count > 0 {
        for feed in results{
            let f = feed as Feed
            savedFeeds.append(f)
            feedNames.append(f.name)
        }
    }

    sidebar = SideBar(sourceView: self.navigationController!.view, menuItems: feedNames)
    sidebar.delegate = self

}


// MARK: - FEED PARSER DELEGATE

func feedParserDidStart(parser: MWFeedParser!) {
    feedItems = [MWFeedItem]()
}

func feedParserDidFinish(parser: MWFeedParser!) {
    self.tableView.reloadData()
}

func feedParser(parser: MWFeedParser!, didParseFeedInfo info: MWFeedInfo!) {
    println(info)
    self.title = info.title
}

func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) {
    feedItems.append(item)
}


// MARK: - SIDEBAR DELEGATE

func sideBarDidSelectMenuButtonAtIndex(index: Int) {
    if index == 0{ // ADD FEED BUTTON
        let alert = UIAlertController(title: "Add new feed", message: "Enter feed name and URL", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
            textField.placeholder = "Feed name"
        })

        alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
            textField.placeholder = "Feed URL"
        })

        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (alertAction:UIAlertAction!) -> Void in
            let textFields = alert.textFields

            let feedNameTextField = textFields?.first as UITextField
            let feedURLTextField = textFields?.last as UITextField

            if feedNameTextField.text != "" && feedURLTextField.text != "" {
                let moc = SwiftCoreDataHelper.managedObjectContext()

                let feed = SwiftCoreDataHelper.insertManagedObject(NSStringFromClass(Feed), managedObjectConect: moc) as Feed

                feed.name = feedNameTextField.text
                feed.url = feedURLTextField.text

                SwiftCoreDataHelper.saveManagedObjectContext(moc)

                self.loadSavedFeeds()
            }
        }))

        self.presentViewController(alert, animated: true, completion: nil)


    }else{
        let moc = SwiftCoreDataHelper.managedObjectContext()

        let selectedFeed = moc.existingObjectWithID(savedFeeds[index - 1].objectID, error: nil) as Feed

        request(selectedFeed.url)


    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    loadSavedFeeds()


}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    request(nil)

}



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

// MARK: - Table view data source

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return feedItems.count
}


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

    cell.itemImageView.image = UIImage(named: "placeholder")


    let item = feedItems[indexPath.row] as MWFeedItem?
    cell.itemAuthorLabel.text = item?.author
    cell.itemTitleLabel.text = item?.title

    if item?.content != nil {

        let htmlContent = item!.content as NSString
        var imageSource = ""

        let rangeOfString = NSMakeRange(0, htmlContent.length)
        let regex = NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: nil, error: nil)

        if htmlContent.length > 0 {
            let match = regex?.firstMatchInString(htmlContent, options: nil, range: rangeOfString)

            if match != nil {
                let imageURL = htmlContent.substringWithRange(match!.rangeAtIndex(2)) as NSString
                println(imageURL)

                if NSString(string: imageURL.lowercaseString).rangeOfString("feedburner").location == NSNotFound {
                    imageSource = imageURL
                }

            }
        }

        if imageSource != "" {
            cell.itemImageView.setImageWithURL(NSURL(string: imageSource), placeholderImage: UIImage(named: "placeholder"))
        }else{
            cell.itemImageView.image = UIImage(named: "placeholder")
        }

    }


    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let item = feedItems[indexPath.row] as MWFeedItem

    let webBrowser = KINWebBrowserViewController()
    let url = NSURL(string: item.link)

    webBrowser.loadURL(url)


    self.navigationController?.pushViewController(webBrowser, animated: true)


}   
}

Feedtableviewcell.Swift

//
//  FeedTableViewCell.swift
//  RSSReader
//
//  Created by Training on 25/12/14.
//  Copyright (c) 2014 Training. All rights reserved.
//

import UIKit

class FeedTableViewCell: UITableViewCell {
@IBOutlet weak var itemTitleLabel: UILabel!
@IBOutlet weak var itemAuthorLabel: UILabel!
@IBOutlet weak var itemImageView: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

Feed. h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Feed : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * url;

@end

I just want to put my xml: http://multpesquisa.com.br/busca/a

How would it look?

1 answer

0


The link you posted despite also being an XML nay is an RSS Feed.

To show him you must:

  • Download the XML
  • Parse XML and Create Your Template
  • Show data on screen

I can see you’re using the MWFeedParser. It won’t be necessary to use it.

There are several ways to make these steps but the most simple sane:

Download the XML

let url = NSURL(string: "http://multpesquisa.com.br/busca/a")

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

    if (error == nil) {
        self.xml = data
    }
    else {
        println("Error: \(error)")
    }

}
task.resume()

Parse XML Create Your Template

Using Xmldictionary this is as simple as

let dictionary = NSDictionary(XMLData: self.xml)
//Estou criando meu modelo aqui ....

Show data on screen

Now that you have the data in your template is very easy! Just show :D

But.. how to lower the images?

The same way you downloaded XML!

And as I show, so?

let image = UIImage(data: data)
self.imageView.image(image)
  • And how do I manipulate items for them? pq in xml has Enterprise, and below enterprise has several items, name, subtitle, icon, link, etc. this example you posted eh to create me another project from scratch? or use the same?

  • This example is to create the project from scratch subtitulo of the third: self.dictionary["empresa"]?[(3-1)]["subtitulo"]

  • self.xml = data this xml comes from where? of the error on this line

  • is a Property that you create var xml : NSData? for example

  • and if I want to show all ? the names and subtitles

  • I sent you the project by email

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.