I'm working on Ios and Swift 3 and I want to parse HTML Code.
Until now Hpple did the trick for me using this code:
func parse_Html_Text(url:String)
{
let data = NSData(contentsOf: URL(string: url)!)
let doc = TFHpple(htmlData: data! as Data!)
}
But when I'm trying to get html code from a query url (like this one: link), then my app crashes and I get Thread1: EXC_BAD_INSTRUCTION error in this line:
let doc = TFHpple(htmlData: data! as Data!)
I also tried Alamofire's request method but I didnt manage to make it work
I'm stucked two days with this so any help will be appreciated.
Thank you in advance!
I noticed that you use Swift 3. Probably the library expects an NSData object but I would suggest to write your function like the following:
func parse_Html_Text(url: String) {
if let safeUrl = URL(string: url) {
let data = try? Data(contentsOf: safeUrl)
let doc = TFHpple(htmlData: data as? NSData)
}
}
In this case keep in mind that we are not handling possible error from the data setter.
Related
I'm trying to test this piece of code to make sure I'm parsing the JSON correctly but the issue I'm running into is that nothing inside of the URLSession code block is getting executed. When I run the program, all I get is the "test2" print statement on the outside. If anyone could help point me in the right direction that would be greatly appreciated, thank you!
import Foundation
struct BMIInfo: Codable {
let bmi: Double
let more: [String]
let risk: String
}
let url = "http://webstrar99.fulton.asu.edu/page3/Service1.svc/calculateBMI?height=60&weight=156"
let urlObj = URL(string: url)
URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
let dataAsString = String(data: data!, encoding: .utf8)
let decoder = JSONDecoder()
let jsonresult = try! decoder.decode(BMIInfo.self, from: data!)
let bmi = jsonresult.bmi
let more = jsonresult.more
let risk = jsonresult.risk
print(bmi)
print(dataAsString)
print("test")
}.resume()
print("test2")
Do you have any other errors? I took your code and put it in a playground and all of the print statements worked. I got 30.463333333333335 for the bmi, and I even added a print statement for risk and got that successfully. The "test2" does print first before any of the others. Do you have anything else going on which could be causing the URLSession to not be able to complete?
This is too simple but I am lost. I am still new to swift really.
I need to parse the downloaded json ( localized file in the Xcode project ) and populate the data to a CollectionView.
enum Response{
case success(Data)
case error(Error)
}
// struct follows the json
struct InformationFromJson: Decodable {
let id: Int
let name: String
}
class MYJSON {
public func downloadMYJSON(_ completion: #escaping (Response) -> ()) {
guard let bundle = Bundle(identifier: MYJSON.bundleId), let path = bundle.path(forResource: "data", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
completion(Response.error(NSError(domain: MYJSON.bundleId, code: MYJSON.bundleErrorCode, userInfo: [NSLocalizedDescriptionKey : MYJSON.bundleError])))
return
}
completion(Response.success(data))
}
}
So, without totally changing the function call, how do I parse the json? It's downloaded so far from the function, but I don't see how to even add a print statement to test, without getting errors because of the guard statement , the way it is.
I need to simple populate a cellForRowAt:
I never saw nested guard like this, so it got me. I am used to seeing the let statements separated so you can put print statements to at least see if things are getting downloaded or parsed.
You can decode your json by passing data, whatever you get from
let data = try? Data(contentsOf: URL(fileURLWithPath: path))
guard let decoded = try? JSONDecoder().decode(InformationFromJson.self, from: data) else {
return
}
I am trying to get JSON image urls from a different endpoint. At the moment I am able to call first endpoint fetching data for exercise name, description and id. Then for each exercise I am trying to call to a different endpoint using an ID value so then I can get image url for the specific exercise.
The only idea I had is to create nested API call to a different endpoint, but I am getting too many syntax errors and it does not work.
The question is how can I reformat my code to remove existing syntax errors.
Here is my code. I never actually seen a way to do this type of API calls.
func parseData() {
fetchedExercise.removeAll()
let url = URL(string: urlPath)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error while parsing JSON")
}
else {
do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {
for eachExercise in exercises {
if eachExercise["license_author"] as! String == "wger.de" {
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
let id = eachExercise["id"] as! Int
}
It has been fixed by adding missing closure brackets at the end which were causing syntax error while trying to run the code.
I'm trying to get the JSON from a website and parse it before printing it.
I've got a class called "JSONImport", which should handle a JSON Import from a server and print it.
A second class should make the call to start the Import and print the content of the JSON.
The following code is what I have so far (I took it from another question Downloading and parsing json in swift)
So this is my "JSONImport.swift":
var data = NSMutableData();
func startConnection(){
let urlPath: String = "http://echo.jsontest.com/key/value";
let url: NSURL = NSURL(string: urlPath)!;
let request: NSURLRequest = NSURLRequest(URL: url);
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!;
connection.start();
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data);
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// throwing an error on the line below (can't figure out where the error message is)
do{
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
print(jsonResult);}
catch {
print("Something went wrong?");
}
}
Inside another class, I would like to print the JSON by:
JSONImport.startConnection();
Now I get an error, because swift wants me to add a parameter to the call, making it look like:
JSONImport.startConnection(<#T##JSONImport#>);
Does someone have an idea, what I should put in there as a parameter?
I am confused, as i didn't declare one.
Thank you all in advance!
Kind regards, Manuel
startConnection() is a instance method, so you need to instantiate an JSONImport to call it.
Only type methods can be used that way. So it's essentially asking for an instance of JSONImport.
Here is how you should do it
let importer = JSONImport()
importer.startConnection()
or by calling from the type method
let importer = JSONImport()
JSONImport.startConnection(importer)
You can read more about instance/type methods at this guide
I am trying to read json date from url and parse it in Tableview using swift. how can I make variable "jsonResult " as global ?
or please guide me how can I populate the tableview with this data from json.
let urlPath = "http://omanevents.net/OmanEventsApp/testPullDate.php"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println("error")
}else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
for var index = 0; index < jsonResult["Events"]?.count ; ++index {
println(jsonResult["Events"]?[index]["Location"])
}
}
})
task.resume()
I would highly recommend that you have a look at this tutorial.
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
It shows you how to deal with core data but in the example it uses adding things to tableView, and saving data for use of the app at later stages. Ray Wnderlich is a great website.