How to uiview into a CPtemplate - swift

I'm trying to replace the map on the carplay app of this sample project by a carplay webview.
Here the function that returns the root template, to be show on CarPlay :
The problem, is that the setRootTemplate function needs a CPTemplate, and I don't know how to create a template and put a uiview on that ?
func application(_ application: UIApplication, didConnectCarInterfaceController interfaceController: CPInterfaceController, to window: CPWindow) {
let webViewClass : AnyObject.Type = NSClassFromString("UIWebView")!
let webViewObject : NSObject.Type = webViewClass as! NSObject.Type
let webview: AnyObject = webViewObject.init()
let url = NSURL(string: "https://www.google.com")
let request = NSURLRequest(url: url! as URL)
webview.loadRequest(request as URLRequest)
let uiview = webview as! UIView
// tried that too... let myCPTemplateHere = webview as! CPTemplate
// Here
interfaceController.setRootTemplate(myCPTemplateHere, animated: true)
}
I tried with WKWebView too
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
Thanks a lot !
PS: This app is for my own usage, I will not send it to the app store.

Related

swift wkwebview is blank page after login

I add wkwebview to load login page :
override func loadView() {
super.loadView()
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
webView.uiDelegate = self
webView.translatesAutoresizingMaskIntoConstraints = false
view = webView
}
and load page with :
let myURL = URL(string: strUrl)
let myRequest = URLRequest(url: myURL!)
self.webView.load(myRequest)
It loaded login page is successful but after logged page is blank ?
I sure that, logged page vie ok on web.

Swift-4 Siren, Update App dialog disappears immediately

I use Siren library to check app version. It shows a dialog to notify there is an update, but after the webview is loaded dialog disappears so user is not able to click anything. How to prevent this?
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
Siren.shared.wail { (results, error) in
if let results = results {
print("AlertAction ", results.alertAction)
print("Localization ", results.localization)
print("LookupModel ", results.lookupModel)
print("UpdateType ", results.updateType)
} else if let error = error {
print(error.localizedDescription)
}
}
}
...
class ViewController: UIViewController , WKUIDelegate , WKScriptMessageHandler, WKNavigationDelegate{
...........
var webView : WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
//let url = URL(string: "http://dev.smartiq.io/mars/mobile/index.html#main" )!
//let url = URL(string: "http://mars.visteknoloji.com/mars/mobile/index.html#main")!
let url = URL(string: "https://dev.smartiq.io/mars/mobile/index.html#main")!
//let url = URL(string: "http://192.168.3.22:8080/mars/mobile/index.html#main")!
webView.scrollView.bounces = false;
webView.load(URLRequest(url: url))
webView.navigationDelegate = self
.....
let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
let date = Date(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
// Do any additional setup after loading the view, typically from a nib.
}
Here I load the wkwebview, when it shows update dialog disappears
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
let controller = WKUserContentController()
controller.add(self ,name : "JSListener")
webConfiguration.userContentController = controller
webView = WKWebView(frame: .zero, configuration: webConfiguration)
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = .gray
webView.uiDelegate = self
view = webView
}

How should you disable a button from being ran over and over upon every click?

I don't know why but I was under the assumption that a button shouldn't be clickable over and over again to redo itself....
I have a fairly simple code.
When my button is clicked, it downloads an image using urlSession into the backgroundview of another viewController and segues into it.
My problem is that if click on button 3 times while I wait for the image to load, my viewController segues 3 layers down into a navigationController and to get back to the original viewController I have to click the back button 3 times. Shouldn't I not be able to segue 3 layers down!?
#IBAction func showImage(_: UIButton) {
loadImage()
}
func loadImage () {
let url = URL(string: "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png")
var request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard let data = data else {
print("You got an error:\(error)")
return
}
let img = UIImage(data: data )
let imgview = UIImageView(image: img)
let sb = UIStoryboard(name: "Main", bundle: nil)
let ivc = sb.instantiateViewController(withIdentifier: "showImage")
ivc.view = imgview
self.navigationController?.pushViewController(ivc, animated: true)
}
session.resume()
}
Thanks to Phillip Mills comment, this is what I have done:
I added a
#IBOutlet weak var showImage: UIButton!
and then upon clicking, I disabled the button with:
showImage.isEnabled = false
And after doing the segue I enabled it again with:
showImage.isEnabled = true
My full code is:
#IBOutlet weak var showImage: UIButton! // Added
#IBAction func showImage(_: UIButton) {
showImage.isEnabled = false // Added
loadImage()
}
func loadImage () {
let url = URL(string: "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png")
var request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard let data = data else {
print("You got an error:\(error)")
return
}
let img = UIImage(data: data )
let imgview = UIImageView(image: img)
let sb = UIStoryboard(name: "Main", bundle: nil)
let ivc = sb.instantiateViewController(withIdentifier: "showImage")
ivc.view = imgview
self.navigationController?.pushViewController(ivc, animated: true)
self.showImage.isEnabled = true // Added
}
session.resume()
}

Swift UIWebView LoadRequest

In order to load urls, I tried to connect .loadRequest with webview, but there is not such loadRequest. Is there anyone who knows why this is occurring to me?
func configurationView(){
if let webData: Web = self.detailItem {
if let webView = self.WebView {
let url = NSURL(string: webData.url)
let urlRequest = NSURLRequest(URL: url!)
(here I am trying to dp WebView.loadRequest(urlRequest), but I cannot!)
}
}
}

Take a full screenshot for all webview in swift

Does anyone know how can I take a full screenshot for all my web view using code in swift ( not the screen ! because the webview is long and we must scroll to view the all content ) and share it via UIActivityViewController?
Try the following code after web view is loaded:
EDITED: run this code in simulator then check the screenshot.jpeg file in your documents app directory
class ViewController: UIViewController,UIWebViewDelegate {
let fileDirectory = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
var urlPath = "http://www.bbc.com/"
let requestUrl = NSURL(string: urlPath)
let request = NSURLRequest(URL: requestUrl!)
webView.loadRequest(request)
webView.delegate = self
}
func webViewDidFinishLoad(webView: UIWebView) {
if (!webView.loading){
var webViewFrame = webView.frame
webView.frame = CGRectMake(webViewFrame.origin.x, webViewFrame.origin.y, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height)
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, false, 0);
self.webView.layer.renderInContext(UIGraphicsGetCurrentContext())
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
var imageData = UIImageJPEGRepresentation(image, 0.7)
var currentFileName = "screenshot.jpeg"
var imageFilePath = fileDirectory[0].stringByAppendingPathComponent(currentFileName)
var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
imageData.writeToURL(imageFileURL!, atomically: false)
webView.frame = webViewFrame
}
}
}
Solution with WKWebView in Swift 5
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
let configuration = WKSnapshotConfiguration()
configuration.rect = CGRect(origin: .zero, size: (self.webView.scrollView.contentSize))
webView.takeSnapshot(with: configuration) {image, error in
if let image = image {
self.saveImage(imageName: "snapshot.jpg", image: image)
}
}
}
}