0% found this document useful (0 votes)
134 views6 pages

Laborator 4 - Simple HTTP Client (Web Service Emulation)

The document describes a mobile application that emulates a web service by programmatically making HTTP requests. The app loads RSS feeds from URLs, allows adding multiple feeds, navigates to full news articles, and saves feeds locally. It displays article titles, dates, short and full descriptions from the loaded feeds. Tapping an title expands the description. The code implements the RSS parsing, network requests, and table view to display the feed items.

Uploaded by

Marcel Lefter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views6 pages

Laborator 4 - Simple HTTP Client (Web Service Emulation)

The document describes a mobile application that emulates a web service by programmatically making HTTP requests. The app loads RSS feeds from URLs, allows adding multiple feeds, navigates to full news articles, and saves feeds locally. It displays article titles, dates, short and full descriptions from the loaded feeds. Tapping an title expands the description. The code implements the RSS parsing, network requests, and table view to display the feed items.

Uploaded by

Marcel Lefter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Ministerul Educației Republicii Moldova

Universitatea Tehnică a Moldovei


Facultatea Calculatoare, Informatică și Microelectronică
Departamentul ISA

Raport
Lucrare de laborator Nr.4
La Programarea Aplicațiilor Mobile

Tema: Simple HTTP Client (Web Service Emulation)

A efectuat:
st. gr. TI-151 FR

A verificat:
lector universitar Antohi Ion

Chișinău 2018
Obiective: De realizat emularea programatică a unui serviciu web.
Scopul: De realizat o aplicație ce va încărca de pe o resursă web (preferată, ex:
https://news.yam.md/ro/rss ) fluxul RSS al acesteia.
Condiții: Serviciul web va fi emulat programatic utilizând metodele protocolului HTTP (GET )
a) posibilitate de adăugare 2 sau mai multe fluxuri RSS
b) posibilitate de a naviga către postarea din fluxul încărcat
c) salvarea locală a fluxului cu păstrarea sa pînă utilizatorul nu o va distruge

În fig. 1 este aplicația care afișează ultimele noutăți de la sursa RSS specificată. Fiecare articol are titlu,
data, descriere pe scurt și descriere pe lung.

Fig. 1
Apăsând pe unul din titluri, descrierea se va extinde de la 3 rânduri pănă la conținutl maxim al acestuia
oferind descrierea deplină. Vezi fig. 2

Fig. 2

Concluzie: Efectuând această lucrare de laborator, am înțeles cum se construiește o aplicație care să
citească informația de pe un site web cu ajutorul RSS.
Anexa
XMLParser
import Foundation

struct RSSItem {
var title: String
var summary: String
var updated: String
}

class FeedParser: NSObject, XMLParserDelegate {


private var rssItems: [RSSItem] = []
private var currentElement = ""

private var currentTitle: String = "" {


didSet {
currentTitle = currentTitle.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
private var currentSummary: String = "" {
didSet {
currentSummary = currentSummary.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
private var currentUpdated: String = "" {
didSet {
currentUpdated = currentUpdated.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
private var parserCompletionHandler: (([RSSItem]) -> Void)?

func parseFeed(url: String, completionHandler: (([RSSItem]) -> Void)?)


{
self.parserCompletionHandler = completionHandler

let request = URLRequest(url: URL(string: url)!)


let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request) { (data, response, error) in
guard let data = data else {
if let error = error {
print(error.localizedDescription)
}

return
}

/// parse our xml data


let parser = XMLParser(data: data)
parser.delegate = self
parser.parse()
}

task.resume()
}

// MARK: - XML Parser Delegate

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,


qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
currentElement = elementName
if currentElement == "entry" {
currentTitle = ""
currentSummary = ""
currentUpdated = ""
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
switch currentElement {
case "title": currentTitle += string
case "summary" : currentSummary += string
case "updated" : currentUpdated += string
default: break
}
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?,


qualifiedName qName: String?) {
if elementName == "entry" {
let rssItem = RSSItem(title: currentTitle, summary: currentSummary, updated:
currentUpdated)
self.rssItems.append(rssItem)
}
}

func parserDidEndDocument(_ parser: XMLParser) {


parserCompletionHandler?(rssItems)
}

func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {


print(parseError.localizedDescription)
}

NewsTableCell
class NewsTableViewCell: UITableViewCell {

@IBOutlet weak var titleLabel:UILabel!


@IBOutlet weak var descriptionLabel:UILabel! {
didSet {
descriptionLabel.numberOfLines = 3
}
}
@IBOutlet weak var dateLabel:UILabel!

var item: RSSItem! {


didSet {
titleLabel.text = item.title
descriptionLabel.text = item.summary
dateLabel.text = item.updated
}
}
}

NewsTableView
class NewsTableViewController: UITableViewController
{
private var rssItems: [RSSItem]?
private var cellStates: [CellState]?

override func viewDidLoad() {


super.viewDidLoad()

tableView.estimatedRowHeight = 155.0
tableView.rowHeight = UITableViewAutomaticDimension

fetchData()
}

private func fetchData()


{
let feedParser = FeedParser()
feedParser.parseFeed(url: "https://news.yam.md/ro/rss") { (rssItems) in
self.rssItems = rssItems
self.cellStates = Array(repeating: .collapsed, count: rssItems.count)

OperationQueue.main.addOperation {
self.tableView.reloadSections(IndexSet(integer: 0), with: .left)
}
}
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {


// Return the number of sections
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
guard let rssItems = rssItems else {
return 0
}

// rssItems
return rssItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->


UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!
NewsTableViewCell
if let item = rssItems?[indexPath.item] {
cell.item = item
cell.selectionStyle = .none

if let cellStates = cellStates {


cell.descriptionLabel.numberOfLines = (cellStates[indexPath.row] == .expanded) ? 0 : 4
}
}

return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)


{
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! NewsTableViewCell

tableView.beginUpdates()
cell.descriptionLabel.numberOfLines = (cell.descriptionLabel.numberOfLines == 0) ? 3 : 0

cellStates?[indexPath.row] = (cell.descriptionLabel.numberOfLines == 0) ? .expanded :


.collapsed

tableView.endUpdates()
}

You might also like