How to Handle Image uploading in WKWebview? - ios

I have use webkit to show url on my app.
when I click on image button(green button in ), it shows
camera or photo library.
issue is, when click Use photo, the webkit
refresh automatically instead showing on page
I have already give photo usage, media, camera permission in plist file
my code is
import UIKit
import WebKit
import Alamofire
class ContinueViewController: UIViewController, WKUIDelegate {
#IBOutlet weak var activityView: UIActivityIndicatorView!
#IBOutlet weak var webview: WKWebView!
func getPostString(params:[String:Any]) -> String{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
var url: URL?
var traderCategoryId = 0, tradeSkillId = 0
override func viewDidLoad() {
super.viewDidLoad()
webview.navigationDelegate = self
self.navigationController?.navigationBar.isHidden = false
webview.uiDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
activityView.startAnimating()
guard let url = self.url else { return }
var req = URLRequest(url: url)
let params = ["id" : id,"trader_skills" : tradeSkillId]
let postString = self.getPostString(params: params)
req.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
req.httpMethod = "POST"
req.httpBody = postString.data(using: .utf8)
self.webview.load(req)
}
}
extension ContinueViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityView.stopAnimating()
}
}
extension UIImagePickerController {
open override func viewDidLoad() {
super.viewDidLoad()
// self.modalPresentationStyle = .fullScreen
}
}

issue is, when click Use photo, the webkit refresh automatically instead showing on page
Because you self.webview.load(req) in
override func viewWillAppear(_ animated: Bool) {
shows camera or photo library, then return to this page
func viewWillAppear called again
self.webview.load(req) called again
do it simple ,
put self.webview.load(req) the relevant in
override func viewDidLoad() {

Related

How to show call dialog when click on action tag?

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/7FUgg.png
I want to open a phone number Alertsheet (like + 91-1234567890) when click call button(phone icon).
my image shows page of web, which is called in my app and i have use WebKit in my code.
what i have tried,
i'm new to webkit help me out.
import UIKit
import WebKit
import Alamofire
class ContinueViewController: UIViewController, WKUIDelegate {
func getPostString(params:[String:Any]) -> String{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
#IBOutlet weak var activityView: UIActivityIndicatorView!
#IBOutlet weak var webview: WKWebView!
var url: URL?
var id = 0, skill = 0
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 14.0, *) {
webview.configuration.defaultWebpagePreferences.allowsContentJavaScript = true
}else {
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
configuration.preferences = preferences
}
webview.navigationDelegate = self
self.navigationController?.navigationBar.isHidden = true
webview.uiDelegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
activityView.startAnimating()
guard let url = self.url else { return }
var req = URLRequest(url: url)
let params = ["id" : id,"skill" : skill]
let postString = self.getPostString(params: params)
req.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
req.httpMethod = "POST"
req.httpBody = postString.data(using: .utf8)
self.webview.load(req)
}
}
extension ContinueViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityView.stopAnimating()
}
}
In your WKNavigationDelegate implementation, you can do something like the following:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, url.scheme == "tel" {
UIApplication.shared.open(url)
decisionHandler(.cancel)
}else {
decisionHandler(.allow)
}
}

How to submit a form in WKWebView Swift?

I've been trying to use WKWebView to fill in a webform and submit. So far I have been able to do that. The problem is the WebView form loop endlessly from "insert element, "trying to submit" to "submited" once I used the below code.
let submitFunction = document.forms[0].submit();
Anyone knows what is happening? How can I rewrite this code?
Thank you very much!
import UIKit
import WebKit
class AnswerVC: UIViewController {
#IBOutlet weak var webView: WKWebView!
var questionText = "1+1"
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
let url:URL = URL(string: "https://gamma.sympy.org/")!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
}
extension AnswerVC: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("insert element")
let scriptFunction = "document.getElementById('id_i').value = '\(questionText)';"
webView.evaluateJavaScript(scriptFunction) { (result, error) in
if error != nil {
ProgressHUD.showError(error as? String)
} else {
print("trying to submit")
let submitFunction = "document.forms[0].submit();"
webView.evaluateJavaScript(submitFunction) { (result, error) in
if error != nil {
print(error?.localizedDescription)
} else {
print("submited")
}
}
}
}
}
}

Two video players appear in UIWebview

Why when I play the video, there are two overlapping video players. Can someone tell me why and how to solve it?
import UIKit
class ViewController: UIViewController,UIWebViewDelegate,UIScrollViewDelegate {
#IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let mediaURL:URL = URL(string: "https://twitter.com/") {
let request:URLRequest = URLRequest(url: mediaURL)
webview.allowsInlineMediaPlayback = false
DispatchQueue.main.async {
self.webview.loadRequest(request)
}
}
}
func webViewDidFinishLoad(_ webView: UIWebView) {
}
}
This is the video image I took

iOS Swift : can't Retrieve current url loaded in UIwebView

i am working in webview application iOS swift :
problem i am facing is i want to get each url which webview displays :
upon urls i have to perform some if else checks . but i could not get the urls which webview loads.
webview is displaying fine results and loading urls upon clicking . i want to fetch all urls which webview navigates on..
import Foundation
import UIKit
class seconVC: UIViewController {
var toPass:String!
var touser:String!
var toPassing:String!
#IBOutlet weak var webV: UIWebView!
#IBOutlet weak var L_back: UIBarButtonItem!
#IBOutlet weak var R_frwrd: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var domurl = toPass;
var username = touser;
var passwing = toPassing;
var sendurl = stringA+username+"/"+passwing;
//exchange login with auth/username/password
println(sendurl);
let url = NSURL (string: sendurl);
let requestObj = NSURLRequest(URL: url!);
webV.userInteractionEnabled = true
webV.loadRequest(requestObj);
}
#IBAction func L_back(sender: UIBarButtonItem) {
if (webV.canGoBack){
webV.goBack()
}
}
#IBAction func R_frwrd(sender: UIBarButtonItem) {
if (webV.canGoForward){
webV.goForward()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
all i want is to get string of current url and navigation buttons for webview :please help ? i referred all the internet no solution is working in my case .
There are couple of UIWebViewDelegate such as shouldStartLoadWithRequest or webViewDidStartLoad or webViewDidFinishLoad or didFailLoadWithError that help you to accomplish your goal. If you want to perform operation after view did finished then implement this delegate method
Swift 3
if let currentURL = webView.request?.url?.absoluteString{
print(currentURL)
}
as it mentioned here.
option-1
let currentURL = webV.request.URL.absoluteString
option-2
get URL in delegate method
func webViewDidFinishLoad(webView: UIWebView){
print(WebView.request?.mainDocumentURL)
}
option-3
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL = webView.request().URL()
print("\(currentURL.description)")
}
or use like
func webViewDidFinishLoad(webView: UIWebView){
let currentURL = webView.request?.URL
}
option-4
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL: = webView.stringByEvaluatingJavaScriptFromString("window.location.href")!
print("\(currentURL)")
}
option-5
func webView(webview: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let currentURL = request.URL.absoluteString
print("\(currentURL)")
}
option-6
func webViewDidFinishLoad(WebVie: UIWebView) {
let currentURL = WebVie.request.mainDocumentURL
print("\(currentURL)")
}
First you have to define the delegate for WebView class. "WebView.delegate = self". Add this code beside one of the function above:
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self }
and for exmaple:
func webViewDidFinishLoad(_ webView: UIWebView) {
if let currentURL = WebView.request?.url?.absoluteString{
print(currentURL)
}
}

Back button not working for my manually loaded UIWebView for external website

Technologies: Swift, iOS8.1.3, XCode 6, Maverick
I've added a "rewind" back button to my UIWebview via the main.storyboard and connected it here on my view with a backButton func:
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
var detailItem: NSURL?
var grabData = false
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.navigationController?.toolbarHidden = false;
}
#IBAction func backButton(sender: AnyObject) {
self.webView.goBack()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let url = self.detailItem {
webView.loadRequest(NSURLRequest(URL: url))
}
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request:
NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if grabData {
grabData = false
return true
} else {
grabData = true
manuallyLoadPage(request)
return false
}
}
func manuallyLoadPage(request: NSURLRequest) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) invar html = NSString(data: data, encoding: NSUTF8StringEncoding) as String
html = html.stringByReplacingOccurrencesOfString("</head>", withString: "<styles><link rel='stylesheet' type='text/css' href='link-to-styles.css' media='all'></styles></head>", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
self.webView.loadHTMLString(html, baseURL: response.URL!)
}
task.resume()
}
My back button doesn't do anything when clicked and I want it to show the previous webpage. I think it has something to do with how I am intercepting the session and manually loading the WebView. Maybe it doesn't know what the original base url is? Something else?

Resources