How to get 2 different webviews with 2 different NSURLSession (iOS Swift) - ios

I want to create a iOS App with 2 Webviews (1 Shop, 1 Logged-In Shop)
If I login in one webview, the other webview includes the same cookies and the first webview is logged in too.
I need the first one to have it's own session (cookies)!
My plan is to have a saved login Touch-ID protected and a free everyone can use webview.
I was currently searching for 2 and a half hours and tried stuff like:
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.my-url.com")!)
request.setValue("", forHTTPHeaderField: "Cookie")
webView.loadRequest(request)

Yes , you can save your cookies to the first webview from webViewDidFinishLoad:
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies as! [NSHTTPCookie]{
print(cookie)
}
NSUserDefaults.standardUserDefaults().synchronize()
If you set to the second webview to the loadRequest:
var req = NSURLRequest(URL: NSURL(string: urlString)!)
var storage = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as! [NSHTTPCookie]
var reqCookies:[AnyObject] = []
for aCookie in storage {
reqCookies += [aCookie]
}
var headers = NSHTTPCookie.requestHeaderFieldsWithCookies(reqCookies)
self.webView.loadRequest(req)
Otherwise you can delete:
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies! {
storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults().synchronize()
EDIT (after comments): to manage different sessions you can look in this Stackoverflow answer to handle your different sessions.

Related

Using HTTPSCookiesStorage can I screen(filter) cookies storage in URLSession?

I have subclassed HTTPCookiesStorage, but the storeCookies() never store the cookies although, i am calling super.storeCookies() within the method.
Session stores the cookies automatically if i dont override the configuration with my custom httpCookiesSession object. I am kind of lost here.
This is the URLSession call
var configration = URLSessionConfiguration.default
//configration.httpCookieStorage = customHTTPCookiesStorage()
let session = URLSession.init(configuration: configration)
if let url = URL.init(string: "https://google.com"){
session.dataTask(with: url) { sip,sap,su in
print(sip,sap,su)
var x = session.configuration.httpCookieStorage?.cookies
}.resume()
}
This is the custom class
class customHTTPCookiesStorage: HTTPCookieStorage {
override func storeCookies(_ cookies: [HTTPCookie], for task: URLSessionTask) {
super.storeCookies(cookies, for: task)
for cookies in cookies{
session?.session.configuration.httpCookieStorage?.setCookie(cookies)
}
print("This is where cookies are stored")
}
}
Update 1
My aim is not to store the cookies in httpcookiesstore when Http response status in 401

Swift : Set custom cookies for Safari app

I have iOS application, that you need to login to, and view some user data...
For some extra edit, I have url link to page, where can user set some special properties,... but it is really annoying for users to login inside page, if they are already logged in application.
For this reason I need to store custom cookies in HTTPCookieStorage, so that when user navigate to the page, authentication cookies would be set for him.
How to create custom cookie with key-value, and store it so that Safari will use it when user navigate to my page?
EDIT
I will provide more information to better understand my situation.
I have one button inside my app.
After clicking to this button, I call API to get valid token.
After receiving token, I need to store this token as cookies. The "server" way of doing this would be
localStorage.setItem('token', this.token)
After I would store this token into HTTPCookieStorage, I will open my page.
UIApplication.shared.open(myURL, options: [:], completionHandler: { (success) in
print("Url open")
})
In page on myURL, the application look for a token cookies. If cookies exist it open web app, else it presents login page.
So my goal is to prevent opening login page.
Store your cookies:
func storeCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
let serverBaseUrl = "http://example.com"
var cookieDict = [String : AnyObject]()
for cookie in cookiesStorage.cookies(for: NSURL(string: serverBaseUrl)! as URL)! {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
userDefaults.set(cookieDict, forKey: "cookiesKey")
}
Retrieve:
func restoreCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
if let cookieDictionary = userDefaults.dictionary(forKey: "cookiesKey") {
for (_, cookieProperties) in cookieDictionary {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
cookiesStorage.setCookie(cookie)
}
}
}
}

How to logout from vk api on ios?

I've integrated login with vk button in my ios app. And I want to add an ability to switch account.
I've tried to run network request to http://api.vk.com/oauth/logout. But it outputs wrong logout hash.
I used this code:
let logoutUrl = "http://api.vk.com/oauth/logout"
let request = NSMutableURLRequest(URL: NSURL(string: logoutUrl)!,
cachePolicy:.ReloadIgnoringLocalCacheData,
timeoutInterval:60.0)
let responseData = try! NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
Also I tried to clear NSDefaults, after logout:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("VKAccessUserId")
defaults.removeObjectForKey("VKAccessToken")
defaults.removeObjectForKey("VKAccessTokenDate")
defaults.synchronize()
And to clear cookies:
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies {
let domainName = cookie.domain
let domainRange = domainName.rangeOfString("vk.com")
if(domainRange.length > 0) {
storage.deleteCookie(cookie)
}
}
And nothing helps
I found the solution. Should call VKSdk.forceLogout()

Load image/file stored in FTP server on WebView

I'm trying to load an image stored in a FTP server on a webview. The problem is that using
let url = "ftp://example.com/images/image1.jpg"
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
only shows a white screen because the FTP server asks for a username and password to grant access. So my question is: how can I authenticate myself so the image from the ftp url loads in the webview?
You can build the URL using this mask.
ftp://username:password#hostname/
let login = "LoginName"
let password = "Password"
let ftpServer = "ftp.server.com"
let fileName = "example.txt"
let ftpUrl = NSURL(string: "ftp://\(login):\(password)#\(ftpServer):21/\(fileName)")

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