Context:
I'm attempting to create an app that populates a UICollectionView (tvOS) based on the contents of a folder in a local server I'm running. The way I'm trying to do this (and it may be completely wrong way) is to 'scrape' the html of my server pages.
I have the following property defined:
let moviesArray: [String] = ["<li>Example 1</li>", "<li>Example 2</li>"]
My UICollectionView will return the number of UICollectionViewCell's equal to moviesArray.count
so I need this number (along with additional data that I won't speak to in this question).
Problem:
The number of files/folders I add to my server is dynamic and will increase / decrease depending on what movies I add to it or delete from it. This will obviously change the html which is returned.
I have the following piece of code that returns the html of my local server's URL and converts it to a string. I then create a substring of that based on a range, and then split out each individual <li>
element from the html. Here's the code:
do {
let url:NSURL? = NSURL(string: "http://localhost:8888/Files/movies/")
// 'contentsOfURL' returns the html code of the page
let html:String? = try NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding) as String
print(html)
// creates a substring of 'html' based on a range defined below
let ulString = html![(html?.startIndex.advancedBy(164))!...(html?.endIndex.advancedBy(-22))!]
print("<ul> substring is: \(ulString)")
// Splits each <li> into a separate string
let liSplit = ulString.characters.split{$0 == "\n"}.map(String.init)
print("li 1 is: \(liSplit[0])")
print("li 2 is: \(liSplit[1])")
print("li 3 is: \(liSplit[2])")
} catch {
print("the error is: \(error)")
}
My Question:
How can I add or remove String
objects to self.moviesArray
based on the number of <li>
elements that are in the html string which is returned? How will I assign each member of liSplit
to self.moviesArray
if it is a dynamic number?
You need to declare you moviesArray
as variable, not as constant and initialize it:
var moviesArray = [String]()
Then you can go ahead and simply add all the retrieved element to it:
moviesArray += liSplit