Login details are not saving in UIWebView in Xcode 9.4? - ios

I want to ask that I am making a UIWebView App in Xcode 9.4?
I didn't add any line of code in AppDelegate. I want to ask that how to implement save session time to keep user logged in on any website. Even if a user closes the app from task manager also...
This is my code in View Controller
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var activity: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
swipeLeftRecognizer.direction = .left
swipeRightRecognizer.direction = .right
webView.addGestureRecognizer(swipeLeftRecognizer)
webView.addGestureRecognizer(swipeRightRecognizer)
loadAddress()
}
#objc private func handleSwipe(recognizer: UISwipeGestureRecognizer) {
if (recognizer.direction == .left) {
if webView.canGoForward {
webView.goForward()
}
}
if (recognizer.direction == .right) {
if webView.canGoBack {
webView.goBack()
}
}
}
func loadAddress() {
let requestURL = NSURL(string: "https://uims.cuchd.in/uims/")
let request = NSURLRequest(url: requestURL! as URL)
webView.loadRequest(request as URLRequest)
}
func webViewDidStartLoad(_ :UIWebView) {
activity.startAnimating()
NSLog("website is loading")
}
func webViewDidFinishLoad(_ :UIWebView){
activity.stopAnimating()
NSLog("website finished loading")
}
}
Please anyone, help me
Thanks in advance

Set httpShouldHandleCookies = true
let requestURL = NSURL(string: "https://uims.cuchd.in/uims/")
let request = NSMutableURLRequest(url: requestURL! as URL)
request.httpShouldHandleCookies = true
Even you should use URL and URLRequest directly instead of converting NSURLRequest to URLRequest & NSURL to URL
let url = URL(string: "https://uims.cuchd.in/uims/")
var request = URLRequest(url: url!)
request.httpShouldHandleCookies = true

Related

How to Handle Image uploading in WKWebview?

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() {

My UIsearch bar does not work/send request to other sites

I'm still new to this but I'm confused on why my search bar does not work any time i put in a url address. I'm trying to make a video downloader app.
import UIKit
import AFNetworking
import Alamofire
class ViewController: UIViewController {
#IBOutlet var Webview: UIWebView!
#IBOutlet var SearchBar: UISearchBar!
override func viewDidLoad() {
if let url = URL(string: "https://www.google.com"){
let requestObj = URLRequest(url: url)
Webview.loadRequest(requestObj)
}
SearchBar.text = "http://"
}
func searchBarSearchButtonClicked(searchbar: UISearchBar) {
searchbar.resignFirstResponder()
let text = SearchBar.text
let url = NSURL(string: text!)
let request:URLRequest = URLRequest(url: url! as URL)
//let request = NSURLRequest(URL: url! as URL)
Webview.loadRequest(request)
}
}
Add UISearchBarDelegate protocol methods to fire a search bar protocol method;
class ViewController: UIViewController, UISearchBarDelegate, UIWebViewDelegate {
override func viewDidLoad() {
SearchBar.delegate = self
webview.delegate = self // connect your webview in storyboard
}
// MARK: - UISearchView Delegates
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
}
func searchBarSearchButtonClicked(searchbar: UISearchBar) {
// call your function here
let searchText = searchbar.text!
let url = URL (string: searchText)
let requestObj = URLRequest(url: url!)
webView.loadRequest(requestObj)
}
}

Intercept javascript file from loading in web view

I am using WKWebView to make a web view app
let url = NSURL(string: "http://www.example.com")
let request = NSURLRequest(url: url! as URL)
homeWebView.load(request as URLRequest)
But I want to intercept some javaScript file of this website before it
loads to change functionality and make the app a bit native looking
Any help would be appreciated.
Thank You.
Following is the complete example. I hope it will help you.
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
private var webView: UIWebView!
override func loadView() {
webView = UIWebView(frame: .zero)
webView.delegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// set the view controller title, navigation etc
self.loadWebPage()
}
func loadWebPage() {
let url = URL(string: "https://www.google.com.pk/")
// let localFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "ExampleHtmlFileName", ofType: "html", inDirectory: "HtmlFilesFolderName")!)
let myRequest = URLRequest(url: url!)
webView.loadRequest(myRequest)
}
//MARK: UIWebView Delegate
func webViewDidFinishLoad(_ webView: UIWebView) {
let jsScript = "exampleJSMethod()"
_ = webView.stringByEvaluatingJavaScript(from: jsScript)
}
}

Swift 2.0 makes error when i try to call in iPhone

When I try to make phone call with my app, Xcode give this error: fatal error: unexpectedly found nil while unwrapping an Optional value
I'm really frustrated and I can't understand why it's doing this. Please take a look at my code and tell me what is wrong.
#IBOutlet var phonenumber: UITextField!
#IBAction func call(sender: UIButton!) {
let phoneN1umber = phonenumber.text
let url = NSURL(string: "tel//:\(phoneN1umber)")!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
}
I would safely unwrap the NSURL :
#IBAction func call(sender: UIButton!) {
let phoneN1umber = phonenumber.text
if let url = NSURL(string: "tel//:\(phoneN1umber)")
{
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
}

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