I'm trying to make it work but nothing.
I want to make (URL textfield) on (RightVC) as (webview)-url on (LeftVC).
I saved the textfield with this code:
#IBAction func save(sender: UIButton) {
NSUserDefaults.standardUserDefaults().setObject(urltxtfield.text, forKey: "urltxtfield")
NSUserDefaults.standardUserDefaults().synchronize()
}
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") != nil {
urltxtfield.text = NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") as? String
} else {
urltxtfield.placeholder = "urltxtfield"
}
}
And it's ok with save. But how to make URL work with LeftVC webview?
This pic to make you understand me:
In your LeftVC (webView), you first need to get the NSUserDefaults and then make a request with your webView.
let prefs = NSUserDefaults.standardUserDefaults()
if let url = prefs.stringForKey("urltxtfield"){
// You have an URL and can make the request
let requestURL = NSURL(string: url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}else{
// Nothing stored in NSUserDefaults
}
Update
After I got the project I updated the reference to the webView from strong to weak and I added the temporary code
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
In info.plist to allow you to browse on websites (you have to check if you want this and I can recommend you to read more about it).
here: some sample of code to call load request to UIWebview when user enter url that urlstring it pass here as parameter Instead of google.com:
UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.cam")!))
OR
let url = NSURL (string: "http://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
Related
I am downloading files from server and showing in my ios device. File type can be any thing like image, pdf etc. and all loading up fine. Now the problem is, some part of file or image is hiding behind the title of page. I want to add margin at top of file after it loads up.
Code I have written to show file:
func openFile(file:String) {
let myBlog = file
let url = NSURL(string: myBlog)
let request = NSURLRequest(url: url! as URL)
webView.load(request as URLRequest)
self.view.addSubview(webView)
let pdfVC = UIViewController()
pdfVC.view.addSubview(webView)
pdfVC.title = "File"
self.navigationController?.pushViewController(pdfVC, animated: true)
self.navigationController!.navigationBar.tintColor = colors.whiteColor
}
I have created webView property within Class like:
var webView : WKWebView!
And inside viewDidLoad(), I have written:
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self
Result I am getting:
Here some part of image is behind the title. I have tried verious solutions given in link add margins in swift, but nothing is working.
My suggestion is to create instance of WKWebView in controller where you need to display it, in your case instance pdfVC
There is can be model, for example:
enum FileType {
case image(fileURL: URL)
case pdf(fileURL: URL)
}
Creating incase of FileViewController and assign fileType to it
func openFile(file:String) {
let pdfViewController = FileViewController()
pdfVC.fileType = FileType.pdf(fileURL: URL(string: "https://www.google.com")!) // example
pdfVC.title = "File"
navigationController?.pushViewController(pdfVC, animated: true)
}
And inside your VC where you need to display a file:
In this way, even if you do have navigationBar you won't have problem with navigationBar and topMargin
class FileViewController: UIViewController {
var fileType: FileType!
override func viewDidLoad() {
super.viewDidLoad()
var urlRequest: URLRequest!
switch fileType {
case .image(let url), .pdf(let url):
urlRequest = URLRequest(url: url)
#unknown default:
break
}
let webView = WKWebView(frame: view.frame)
webView.load(urlRequest)
self.view = webView
}
}
Hope this will help you!
use Bounds instead of Frame
webView = WKWebView(frame: self.view.Bounds)
How can you check to see if a URL is valid in Swift 4? I'm building a simple web browser for personal use and even though I know to enter the full URL each time I'd rather get an alert instead of the app crashing if I forget.
import UIKit
import SafariServices
class MainViewController: UIViewController {
#IBOutlet weak var urlTextField: UITextField!
#IBAction func startBrowser(_ sender: Any) {
if let url = self.urlTextField.text {
let sfViewController = SFSafariViewController(url: NSURL(string: url)! as URL)
self.present(sfViewController, animated: true, completion: nil)
}
print ("Now browsing in SFSafariViewController")
}
}
For example, if I was to type in a web address without http:// or https:// the app would crash with the error 'NSInvalidArgumentException', reason: 'The specified URL has an unsupported scheme. Only HTTP and HTTPS URLs are supported.'
Reading the comments on the accepted answer, I could see that you actually want to validate the URL, to check if it's valid before trying to open with Safari to prevent any crash.
You can use regex to validate the string(I created an extension, so on any string, you can check if it is a valid URL):
extension String {
func validateUrl () -> Bool {
let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
return NSPredicate(format: "SELF MATCHES %#", urlRegEx).evaluate(with: self)
}
}
You're probably crashing because you're using the ! operator and not checking that it will work. Instead try:
#IBAction func startBrowser(_ sender: Any) {
if let urlString = self.urlTextField.text {
let url: URL?
if urlString.hasPrefix("http://") {
url = URL(string: urlString)
} else {
url = URL(string: "http://" + urlString)
}
if let url = url {
let sfViewController = SFSafariViewController(url: url)
self.present(sfViewController, animated: true, completion: nil)
print ("Now browsing in SFSafariViewController")
}
}
}
This should give you the idea of how to handle the different cases, but you probably want something more sophisticated which can deal with https and strips whitespace.
I want to open an iOS app_B from app_A and then wants the data of app_B back into app_A, tried below to open whatsapp, but didn't work. Please help how to achieve this in iOS, thanks in advance.
#IBAction func clickMe(_ sender: UIButton) {
let url = "https://api.whatsapp.com/send?00919599****** "
let whatUpUrl = NSURL(string: url)
if UIApplication.shared.canOpenURL(whatUpUrl! as URL){
UIApplication.shared.openURL(whatUpUrl! as URL)
} else {
//redirect to safari because the user doesn't have Whatsapp installed
UIApplication.shared.openURL(NSURL(string: "http://whatsapp.com/")! as URL)
}
}
WebUrl Link open Chat
let whatsappURL = URL(string: "https://api.whatsapp.com/send?phone=9512347895&text=Invitation")
if UIApplication.shared.canOpenURL(whatsappURL!) {
UIApplication.shared.openURL(whatsappURL!)
}
Note: Add url scheme in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
Add this to Info.plist
Then on the button you want to open whatsapp use this.
#IBAction func whatsappButtonPressed(_ sender: Any) {
var str = "Hello to whatsapp"
str = str.addingPercentEncoding(withAllowedCharacters: (NSCharacterSet.urlQueryAllowed))!
let whatsappURL = NSURL(string: "whatsapp://send?text=\(str)")
if UIApplication.shared.canOpenURL(whatsappURL! as URL) {
UIApplication.shared.openURL(whatsappURL! as URL)
} else {
showAlert(message: "Whatsapp is not installed on this device. Please install Whatsapp and try again.")
}
}
Similarly for other apps :
Replace -
NSURL(string: "whatsapp://send?text=(str)") with
NSURL(string: "APPNAME://").
You will also need to add that app to Info.plist as described above.
Thanks!!
I am loading a url in a UIWebView as below:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MainWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.odysseynewsmagazine.net")
let request = NSURLRequest(url:url! as URL)
self.MainWebView!.loadRequest(request as URLRequest)
}
}
IBOutlet is connected and my .plist has App Transport Security Settings and Allow Arbitrary Loads set to YES.
Why is the app building a blank page?
Try
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.google.com")! // it works ? Comment line and uncomment the following one
// let url = URL(string: "http://www.odysseynewsmagazine.net")!
let request = URLRequest(url: url)
mainWebView.load(request) // var should start with lower case
}
If it works, change the URL. If it doesn't work only with your URL then there's something wrong with either the site or ATS. Paste the console output.
Ok. So here is the normal web-view loading your URL with just the App transport security setting
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://www.odysseynewsmagazine.net")
let request = NSURLRequest(url:url! as URL)
self.webView.loadRequest(request as URLRequest)
}
And the plist setting set to
Allow Arbitrary Loads to YES.
And result is:
Your code is just fine!!!
Your issue is you have missed add NSAllowsArbitraryLoadsInWebContent key in your NSAppTransportSecurity dictionary and set value to TRUE
To fix this you only need replicate the below image in your plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
</dict>
Your webView rendering the webView content, your code is unchanged
Hope this helps
I'd like to load a web page into a UIWebView, using URLSession.
An ephemeral session, indeed, because i wouldn't like to store the session if, for example, i've a login on Twitter/FB/whatever site.
So, i've a UIWebView named webPage
#IBOutlet var webPage: UIWebView!
a UITextField, where i can write the URL
#IBOutlet var urlField: UITextField!
Next to this text field, i've a UIButton, that implements this action
#IBAction func sendUrl(_ sender: Any) {
let stringUrl = urlField.text
let url = URL (string: stringUrl!)
openPageWithSession(url: url!)
}
and the function openPageWithSession, where i use the ephemeral session
func openPageWithSession(url: URL){
let request = URLRequest(url: url)
let ephemeralConfiguration = URLSessionConfiguration.ephemeral
let ephemeralSession = URLSession(configuration: ephemeralConfiguration)
let task = ephemeralSession.dataTask(with: request) { (data, response, error) in
if error == nil {
self.webPage.loadRequest(request)
} else {
print("ERROR: \(error)")
}
}
task.resume()
}
The loading of the web page it's ok. But if i've a login on Twitter and after that i kill the app, if i reopen the app and navigate Twitter again, i'm already logged in!
Why? The ephemeral session is not invalidate after a kill?
From the comments above.
Instead of self.webPage.loadRequest(request), you should use:
self.webView.load(data, mimeType: "text/html", textEncodingName: "", baseURL: url).
This way you'll be using the ephemeral session you created. Otherwise you're just loading the web view normally, without the ephemeral session at all.