The following is what I am trying to do:
- Go to a website;
- Read the website content into a String;
- Identify substrings with specific content (multiple hyperlinks);
- Save the list of hyperlinks as an array of Strings.
This is how I am trying to do it:
// Reads a web page into a string and returns a list of hyperlinks
func readWebToString(completion: @escaping ([String]) -> ())
{
var finalResult = [String]()
guard let dataURL = URL(string: self.GRIB_URL)
else
{
print("Error")
return completion(["N/A"])
}
do
{
var contents = ""
let request = URLRequest(url: dataURL)
let session = URLSession.shared
let task = session.dataTask(with: request) {(data, response, error) -> Void in
if (data != nil)
{
contents = String(data: data!, encoding:String.Encoding.utf8)!
print("CONTENTS1:",contents)
let expression : String = ">gfs\\.\\d+<"
let range = NSRange(location: 0, length: contents.characters.count)
do
{
let regex = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive)
let contentsNS = contents as NSString
let matches = regex.matches(in: contents, options: [], range: range)
for match in matches
{
for i in 0..<match.numberOfRanges
{
let resultingNS = contentsNS.substring(with: (match.rangeAt(i))) as String
finalResult.append(resultingNS)
}
}
if (!finalResult.isEmpty)
{
for i in 0..<finalResult.count
{
finalResult[i].remove(at: finalResult[i].startIndex)
finalResult[i].remove(at: finalResult[i].index(before: finalResult[i].endIndex))
}
}
completion(finalResult)
}
catch
{
print("No regex match")
}
}
else
{
print("No data")
}
}
task.resume()
}
}
func makeGribWebAddress() -> [String]
{
var finalResult = [String]()
let address1 = "h t t p://xxxxxxxxx"
let address2 = "xxxxx";
let address4 = "xxxx"
let address5 = "xxxxxx"
print("CONTENTS2:")
readWebToString() {listOfFiles in
if (!listOfFiles.isEmpty)
{
for i in 0..<listOfFiles.count
{
let address6 = xxxxxx"+listOfFiles[i]
let address3 = listOfFiles[i].substring(from:listOfFiles[i].index(listOfFiles[i].endIndex, offsetBy: -2))
let addressFull = (address1 + address2 + address3 + address4 + address5 + address6).trimmingCharacters(in: .whitespacesAndNewlines)
finalResult.append(addressFull)
}
}
}
print("CONTENTS3:",finalResult)
return finalResult;
}
Unfortunately, it does not work. My output is as follows:
CONTENTS2:
CONTENTS3: []
CONTENTS1: website content read successfully
Obviously, the completion is not handled correctly. Any suggestions?
Thank you!