How to load HTML string in browser in swift 2? - html

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)

Related

Web content returned differently between Obj-C and Swift

I am grabbing the html from facebook.com in two apps, one Obj-C and the other Swift. But simulators are logged in and thus a cookie is stored and the sites show a valid account. The issue is the Swift app is returning differing html, not complete with user information. Obj-C using UIWebView, Swift using WKWebView. The code grabbing the html is independent from the web control.
If i run the Swift app from the real device, i get the correct html. I am not seeing why this is occurring. Thoughts?
Obj-C:
var htmlString: String = ""
let requestURL = URL(string: "https://www.facebook.com")
do {
htmlString = try String(contentsOf: requestURL!, encoding: .ascii)
} catch let error {
print(error)
}
Swift:
NSURL *requestURL = [NSURL URLWithString: #"https://www.facebook.com"];
NSError *error;
htmlString = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];

swift 4 error: load html string to webview

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")
}
}

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 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"]