swift 4 error: load html string to webview - html

I tried to load a html string in my webview with the code :
let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
self.weview.loadHTMLString(html, baseURL: nil)
I run the app, everything works fine, but if i press on a website link, i get the error in my AppDelegate: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
Can someone give me a code for swift 4, where I can load a html string and interact with it? Would be really nice.

First thing to check - go to Project Settings -> Build Phases -> Copy Bundle Resources to make sure your directory with your html-files is on the list there.
Second, load the file the way listed below. You don't have to load the content of the file.
let path = Bundle.main.path(forResource: "code", ofType: "html")!
let uri = URL(string: path)!
let request = URLRequest(url: uri)
webView.loadRequest(request)
Also, make sure forResource param contains full path to the html file starting from your project directory

Try This :
let link = "https://google.co.in"
do {
let htmlStr = try String(contentsOf : URL(string:link)!)
let separateHtmlStr = htmlStr.components(separatedBy:"") // any html tag you want to interact with
let newURL = URL(string: link)
yourWebView.loadHTMLString(separateHtmlStr, baseURL: newURL) // in case if you have changed anything
}catch{
print("Exception")
}
}

Related

WebView insert local image to html couldn't success?

I have a WkWebView in my ViewController, I used webview load local html. The code is this:
guard let path = Bundle.main.url(forResource: "editor", withExtension: "html") else {
return
}
webView.load(URLRequest(url: path))
1: I choose a image from photoLibrary, then I saved it to document's directory .
private func fileName() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd#HH-mm-ss"
return "/" + formatter.string(from: date) + ".png"
}
func saveImage(_ image: UIImage) {
guard let imageData = UIImageJPEGRepresentation(image, 1.0) else {
return
}
let directory = NSHomeDirectory().appending("/Documents")
let path = directory.appending(fileName())
let fileManager = FileManager.default
do {
try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
fileManager.createFile(atPath: path, contents: imageData, attributes: nil)
} catch {
SHLog("saveImage: \(error)")
}
}
2: I fetched the image path then I used the method of the webView to insert the image.
func evaluateJs(_ imagePath: String) {
webView.evaluateJavaScript("insertImage('\(imagePath)')") { (response, error) in
}
}
insertImage() is a method from the local js file, it can insert the image to html.
If I used the local imagePath, I couldn't insert image to html. But When I used the real url, it can work. I don't know the reason, anyone could help me. Thanks.
Your issue is likely caused by WKWebViews security policies not allowing you access to the local folders of the application.
Check out the documentation for WKWebView loadFileURL. You should be able to pass either the documents directory or full image URL in the allowingReadAccessTo parameter which should let you access the images you want.
If you have a web url of the image, I would prefer to use the web URL anyway rather than trying to store and load the image locally. Your not using up storage in your documents directory and WKWebView is designed to load content from the web.
In my case, assign baseURL your image file's parent folder firstly. Then insert the whole URL path in your html likes following.
<img src="/var/mobile/Containers/Data/Application/C217F3BD-1A1B-438A-A436-D878411C7849/Documents/48C4B007-A950-46D2-A719-E025482710A0/images/79042B1F-E11C-42D1-8B49-DD3A0016F421.jpg"

Get HTML from query url (index.php?[arguments] ) Swift 3 ios

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.

How to load HTML string in browser in swift 2?

To load HTML string in webview I use that code
webView.loadHTMLString(embeddedString, baseURL: nil)
How can I load HTML string in browser like safari or chrome when a tableViewCell is tapped?
You can implement this may be work
let fileURL = NSURL(fileURLWithPath: "UrlOfYourFileWhereToLoad")
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)

Correct way to place and handle .json file in Xcode

I just started to learn Swift and xcode and the first problem that I'm facing is how and where should I place the json file ? And how to use those files? Should I place the .json files within Assets folder ? Since I find it difficult, I would love to hear some tips or examples from you !
You can add an empty file, select syntax coloring as JSON and paste your json text. Even if it is not formatted, you can format it by selecting all the text and pressing Ctrl + I.
How I've done this in September 2019...
1) In Xcode, create an Empty file. Give the file a .json suffix
2) Type in or paste in your JSON
3) Click Editor -> Syntax Coloring -> JSON
4) Inside the file, highlight the JSON, click ctrl + i to indent
5) import SwiftyJSON using Cocoapods
6) In your ViewController, write...
guard let path = Bundle.main.path(forResource: "File", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSON(data: data)
} catch {
print(error)
}
N.B. - "File" is the name of the file you created, but excluding the .json suffix
See SwiftyJSON GitHub page for more info - https://github.com/SwiftyJSON/SwiftyJSON
Please review the below image to check where to place the file.
I suggest you to create a group and add the file in that.
After that, review the below could for using that file.
Edit: This is the updated code for Swift 5 if that helps anyone.
let path = Bundle.main.path(forResource: "filename", ofType: "json")
let jsonData = try? NSData(contentsOfFile: path!, options: NSData.ReadingOptions.mappedIfSafe)
var location = "test"
var fileType = "json"
if let path = Bundle.main.path(forResource: location, ofType: fileType) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
}
} catch let error {
print(error.localizedDescription)
}}
As per your requirement, you want to read json from that json file.
I am using SWIFTY JSON Library for that.
Find below the link for that
https://github.com/SwiftyJSON/SwiftyJSON
Add this library to your project.
After adding it, now review the below code:-
let json = JSON(data: jsonData!)
for (index, subjson): (String, JSON) in json{
let value = subjson["key"].stringValue
}

How to parse the data from JSON iOS

I am building an app in iOS using SWIFT and i have also been using swiftyJSON to make this project a little easier.
func parseJSON(){
let path : String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let url : String = "http://www.thegoodsite.org/attend/api.php?users_id=1"
let nsurly = NSURL(string: url)
let jsonData = NSData(contentsOfURL: nsurly!) as NSData!
let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
var Name = readableJSON
numberOfRows = readableJSON["People"].count //Ignore this for the question
NSLog("\(Name)")
}
I am loading this data from a url so if going to include a picuture of the data im getting back in the console.
CLICK THIS LINK TO SEE IMAGE OF WHAT THE CONSOLE SAYS
So what code do i need to add to get the email to come out as text.
var Name = readableJSON ["users","email"]
However when I do that to the code I seems not to get any data at all.
How can I edit this code to get the email like I want?
let users = readableJSON["users"]
let user = users[0] // get info of the first user, you should check more here
let email = user["email"]
Or (as #nhgrif's cmt):
if let users = readableJSON["users"], user = users.first, email = user["email"]
I play the code,then i found the result of Json if Dictionary, so use the var Name = readableJSON["users"]!![0]["email"]