I want to get data from a news website without RSS Feed, I just want to get titles name, And i am using this code -
var url = NSURL(string: "http://www.gulf-times.com/stories/c/192/0/Sport")
if url != nil {
let task = URLSession.shared.dataTask(with: url! as URL, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) as NSString!
print(urlContent)
}
})
task.resume()
}
Problem is that, I am unable to get titles value-
If you are comfortable with RegEx then use following pattern
/title = "(.*)"/g
This will give you all the titles.
Modified:
Please use like below
let matched = matches(for: "title = \"(.*)\"", in: contentOfPage)
matches : Function
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
Getting following result
[
"title = \"Al-Khelaifi voted Asian tennis Chairman\"",
"title = \"Dimitrov downs Goffin for ATP Tour Finals crown\"",
"title = \"Coach Lehmann calls for Australia to get behind Ashes selection\"",
"title = \"Federer expects great things from returning trio\"",
"title = \"Whateley wins Air Maroc League second stage\"",
"title = \"Qatar-based Frijns finishes strong as Oliphant wins\"",
"title = \"Sutton faces tough road ahead to get Chinese on track\"",
"title = \"Qatar, Japan sign deal to import, export race horses\"",
"title = \"Islanders deny Lightning comeback for third straight win\"",
"title = \"Curry leads Golden Warriors fightback after Sixers blitz\"",
"title = \"Fleetwood claims European Order of Merit as Rose falters\"",
"title = \"Challengers win thriller against City Exchange\""
]