UIWebView windows authentication in swift programming - ios

I have a problem with the UIWebView. I cant open a Website with Windows Authentication... In the Safari Browser a pop-up appears, therefor in the WebView Control happened nothing.
Can someone help me with this problem?
Here my code
class MainViewController: UIViewController, UIWebViewDelegate, MFMailComposeViewControllerDelegate {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad();
webView.delegate = self;
let url = NSURL (string: "http://test.raphaels.com/mobile/");
let requestObj = NSURLRequest(URL: url);
webView.loadRequest(requestObj);
}
}
This piece code of works perfectly fine on non-secure server(URL) on iOS simulator, thats iPhone simulator/emulator on Xcode. But when I use the above URL(can only be accessed from intranet). It asks for username/password in browser and stops in iPhone emulator. Please help me, how can i supply username and password. I searched on internet and found many examples, unfortunately none of them was in swift programming.
I tried to write a solution which fails, so below is the failing code
override func viewDidLoad() {
super.viewDidLoad();
webView.delegate = self;
let username = "username11";
let password = "password22";
let loginString = NSString(format: "%#:%#", username, password);
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!;
let base64LoginString = loginData.base64EncodedStringWithOptions(nil);
// create the request
let url = NSURL (string: "http://test.raphaels.com/mobile/");
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
webView.loadRequest(request);
}

And it worked :-) With below piece of code.
override func viewDidLoad() {
super.viewDidLoad();
webView.delegate = self;
let urlComponents = NSURLComponents(string: "http://test.raphaels.com/mobile/");
urlComponents.user = "username11";
urlComponents.password = "password22";
let url = urlComponents.URL;
let requestObj = NSURLRequest(URL: url!);
webView.loadRequest(requestObj);
}

Objective C version
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:#"http://test.raphaels.com/mobile/"];
[urlComponents setUser:#"username11"];
[urlComponents setPassword:#"password22"];
NSURL *url = [urlComponents URL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];

A quick and easy solution is: use URL as
http://username:password#test.raphaels.com/mobile/
No need for any special code.

Related

Why does using Nsurl request keeps telling me to rename to "init(url)"

Also trying to add the ability to detect a video and download it to the application in short a web-based app used for download any kind of video and has the ability to store it within the app
import UIKit
class ViewController: UIViewController {
#IBOutlet var Webview: UIWebView!
#IBOutlet var SearchBar: UISearchBar!
override func viewDidLoad() {
let url = NSURL(string: "https://www.google.com")
let request = NSURLRequest(URL: url! as URL) Webview.loadRequest(request)
SearchBar.text = "http://"
}
func searchBarSearchButtonClicked(searchbar: UISearchBar) {
searchbar.resignFirstResponder()
let text = SearchBar.text
let url = NSURL(string: text!)
let urlRequest:URLRequest = URLRequest(url: url! as URL)
// let request = NSURLRequest(URL: url! as URL)
Webview.loadRequest(urlRequest)
}
}
You need to use like this in swift
if let url = URL(string: "https://www.google.com"){
let requestObj = URLRequest(url: url)
Webview.loadRequest(requestObj)
}
URL :
URL is a swift struct, so is passed by value.
NSURL :
NSURL is an Objective-C class. Is inherits from NSObject
In general, prefer the new struct versions of things unless you need to subclass for some reason.
An object representing the location of a resource that bridges to URL; use NSURL when you need reference semantics or other Foundation-specific behavior.
Both URL and NSURL is accepted in swift. but you have used swift then most refer URL MORE.
Use URL and URLRequest instead NSURL and NSURLRequest in Swift.
let url = URL.init(string: "https://www.google.com")
let request = URLRequest.init(url: url!)
Webview.loadRequest(request)
For Reference you can refer : Reference

`UIApplication.shared.canOpenURL(:)` method not working on iOS 11.4 (iPad Devices Only)?

Why UIApplication.shared.canOpenURL(:) method not working on iOS 11.4 - iPad Devices? although it's working fine on iOS 11 & 12.0 [iPhone devices]!
Note:
Code written in Swift 4.2
Passed url is valid
I use https
Ok, Bro, I had the same problem with facebook open share link and I solve the problem when I change the shareDialog.mode to .automatic
So you can try this way and tell me if it works?
let url = URL(string: "www.google.com")
let content = LinkShareContent(url: url, quote: "Google")
let shareDialog = ShareDialog(content: content)
shareDialog.mode = .automatic
shareDialog.presentingViewController = self
shareDialog.failsOnInvalidData = true
shareDialog.completion = { result in
}
do {
try shareDialog.show()
} catch {
print("Error")
}
as our discussion, you need to open a web view in your app
so you can add this
import UIKit
class WebVC: UIViewController {
#IBOutlet weak var webView: UIWebView!
var url = ""
var firstLoad = true
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
func setup() {
self.webView.backgroundColor = Color.white.value
self.webView.delegate = self
var urlRequest = URLRequest(url: URL(string: url)!)
urlRequest.cachePolicy = .reloadIgnoringCacheData
self.webView.loadRequest(urlRequest)
}
}
and in your controller, you can use
func openWebView() {
let webVC = WebVC()
webVC.url = "www.google.com"
webVC.title = "Google"
self.navigationController?.pushViewController(webVC, animated: true)
}

UIWebView Windows Authentication SWIFT

I have a problem with the UIWebView. I cant open a Website with Windows Authentication... In the Safari Browser a pop-up appears, therefor in the WebView Control happened nothing.
Can someone help me with this problem?
Here my code:
let url = NSURL (string: "http://inside.domain.com");
let requestObj = NSURLRequest(URL: url!);
browser.loadRequest(requestObj);
I also set the Info.plist.....
Thanks for helping
I am assuming that your username is myUserName and password is myPassword
Now modifying your piece of code
let urlComponents = NSURLComponents(string: "http://inside.domain.com");
urlComponents.user = "myUserName";
urlComponents.password = "myPassword";
let url = urlComponents.URL;
let requestObj = NSURLRequest(URL: url!);
browser.loadRequest(requestObj);

How do I properly cache a NSURLRequest in swift?

Forgive if this has been asked but I've done heavy searching and can't seem to find an answer I'm looking for in swift. I have a UIWebView that loads PDF files and I wouldn't want the user to go through a tedious loading process again if they exit the WebView and come back, so how do I cache a request to make the loading quicker?
Here is my code:
var contentUrlPassedOn: String!
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
let url: NSURL! = NSURL(string: contentUrlPassedOn)
myWebView.loadRequest(NSURLRequest(URL: url))
var request: NSURLRequest
}
UPDATE
What I am trying to accomplish can be seen in this video
that is an example of dropbox's iOS app. When one of the files have been already loaded, every other trip into that file ( in this case PDF) will be quick and easy. This method is exactly what I am trying to replicate.
any suggestions?
GIF
The first time you enter this ViewController,you can see download progress
Then second time, it just load local file.So it is very quick
And code
class ViewController: UIViewController,NSURLSessionDownloadDelegate{
var sesson:NSURLSession!
var webview:UIWebView!
var progressView:UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
self.sesson = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
self.webview = UIWebView(frame: self.view.frame)
self.view.addSubview(webview)
let documentDir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first as! NSURL
let pdfFilePath = documentDir.URLByAppendingPathComponent("Test.pdf");
if NSFileManager.defaultManager().fileExistsAtPath(pdfFilePath.path!){
let request = NSURLRequest(URL: pdfFilePath)
webview.loadRequest(request)
}else{
progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default);
progressView.frame = CGRectMake(0, 0,200, 4)
progressView.progress = 0
progressView.progressTintColor = UIColor.blueColor()
progressView.center = self.view.center
self.view.addSubview(progressView)
let remoteURL = "https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.pdf"
let request = NSURLRequest(URL: NSURL(string: remoteURL)!)
let downloadTask = self.sesson.downloadTaskWithRequest(request)
downloadTask.resume()
}
// Do any additional setup after loading the view, typically from a nib.
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if progressView != nil{
progressView.removeFromSuperview()
}
let documentDir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first as! NSURL
let pdfFilePath = documentDir.URLByAppendingPathComponent("Test.pdf");
NSFileManager.defaultManager().moveItemAtURL(location, toURL: pdfFilePath, error: nil)
let request = NSURLRequest(URL: pdfFilePath)
self.webview.loadRequest(request)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
var curprogress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
progressView.progress = curprogress
}
}
NSURLConnection (and NSURLSession's shared session) uses a shared cache. You can configure the policies of that cache to use on-disk storage, but my vague recollection is that iOS uses only an in-memory cache by default. Have a look at the NSURLCache class, and do the Swift equivalent of:
NSString *myPath = ... // some subdirectory in your app's caches directory
NSURLCache *cache = [[NSURLCache alloc] initWithCapacity:2048576 /* 2M */
diskCapacity: 134217728 /* 128M */
path:myPath];
[NSURLCache setSharedURLCache:cache];
or whatever, and you'll probably have better luck.
Note that the on-disk cache in iOS is still temporary, and can be deleted by the OS, but only when your app is not running (assuming that hasn't changed recently).
Something like
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String
var dir = cacheDir.stringByAppendingFormat("/urlCache/")
var cache = NSURLCache(memoryCapacity: 2048576,
diskCapacity: 134217728,
path: dir)
NSURLCache.setSharedURLCache(cache)
but I'm not all that familiar with Swift, so I could be getting the syntax wrong.

Controlling UIWebView

In my IOS app i am using a webview to play audio from my website. My problem is that webview plays automatically when i don't even click on the webview. It says in the ios docs that mediaPlaybackRequiresUserAction is equal to true by default but it still plays. I have tried even setting mediaPlaybackRequiresUserAction to true in my code but that still doesn't solve the problem. I need to stop it from playing without user action because when the user goes to the next screen the webview automatically plays the audio. I have looked around on stack overflow and none of the solutions i found seem to help with this problem.
Here is my code:
//function to get NSURLrequest
func configureView() -> NSURLRequest {
let fileNameDownload: AnyObject = self.detailItem!
let fileNameURL = (fileNameDownload as NSString)
let spaces = fileNameURL.componentsSeparatedByString(" ")
if (spaces.count > 0) {
let fileNameURL = fileNameURL.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, fileNameURL.length))
println(fileNameURL)
let url = NSURL(string: fileNameURL)
let request = NSURLRequest(URL: url!)
return request
}
else {
let url = NSURL(string: fileNameURL)
let request = NSURLRequest(URL: url!)
return request
}
}
override func viewDidLoad() {
super.viewDidLoad()
previewWebView.loadRequest(configureView())
}

Resources