swift3 wkwebview not working on certain devices - swift3

Any ideas why wkwebview would not work on certain devices? I am able to open the url in safari on the device but there is no network request when going through the app.
var webView: WKWebView!
let myURL = URL(string: "https://mywebsitehere/" )
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
Is there some setting on a phone that could be blocking this? I have tried with 2 iPhone 6's running iOS 10 on the same network. One works and the other goes nowhere.

Related

ASWebAuthenticationSession/Azure AD B2C - Error: The provided scheme is not valid. A scheme > should not include special characters such as ":" or "/"

I am getting this error:
[AuthenticationSession] The provided scheme is not valid. A scheme
should not include special characters such as ":" or "/".
When trying to use ASWebAuthenticationSession for a SwiftUI project:
let authURL = URL(string: "https://login.microsoftonline.com/common")
let scheme = "msauth.com.xxxxxxx.Test1://auth"
self.session = ASWebAuthenticationSession.init(url: authURL!, callbackURLScheme: scheme, completionHandler: { callbackURL, error in
guard error == nil, let successURL = callbackURL else {
return
}
let oauthToken = URLComponents(string: (successURL.absoluteString))?.queryItems?.filter({$0.name == "code"}).first
print(oauthToken ?? "No OAuth Token")
})
The oAuth provider is Azure AD B2C where I have configured a mobile app for iOS / macOS.
I have followed these examples for:
Using ASWebAuthenticationSession with SwiftUI
ASWebAuthenticationSession for Web Login in iOS App
I have stayed away from the MSAL sample in GitHub because there is no SwiftUI example and the issue has been outstanding for a year.
Maybe I should choose a different option for AuthenticationServices:

Is setting up a cookie with WKWebsiteDataStore too late?

I need to set a cookie in a WKWebView on both iOS 10 an iOS 11. After reading this, I wrote different code for the 2 iOS versions, using a JavaScript script in iOS 10 and WKWebsiteDataStore in iOS 11.
While using iOS 10 I have no issue, with iOS 11 the web app sees the cookie I used in the previous session. I mean, if the first time I launch the app the cookie value is "A", the web app doesn't see the cookie; if I close the app and relaunch it with "B" as the new value of the cookie, the web app now reads "A" from the cookie. However, with the Web Inspector I see the right value of the cookie.
It seems that with the WKWebsiteDataStore the cookie is set too late; how can I solve this issue (without using the same code used in iOS 10 even in iOS 11)?
My code is:
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
let userContentController = WKUserContentController()
configuration.preferences = preferences
if #available(iOS 11, *) {
if let cookie = cookie {
let dataStore = WKWebsiteDataStore.default()
dataStore.httpCookieStore.setCookie(cookie) {
configuration.websiteDataStore = dataStore
configuration.userContentController = userContentController
self.createAndLoadWebView(with: configuration)
}
}
} else {
if let cookie = cookie {
let script = getJSCookiesString(for: [cookie])
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
configuration.userContentController = userContentController
createAndLoadWebView(with: configuration)
}
}
And then:
private func createAndLoadWebView(with configuration: WKWebViewConfiguration) {
webView = WKWebView(frame: self.containerView.frame, configuration: configuration)
self.containerView.addSubview(webView)
let req = URLRequest(url: pageUrl)
webView.load(req)
}
Add same cookies in Request header, i faced same problem but after add cookies in header request page load normally.

Set Cookie with Swift 3

I am struggling to set a cookie using Swift 3 into a WKWebView. I could not find any example using Swift 3 so using Swift - How to set cookie in NSMutableURLRequest as a starting point, this is what I have:
let url = URL(string: "https://s3-us-west-2.amazonaws.com/foo/helloworld.html")
/* Create cookie and place in cookie storage */
let cookieStorage = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "somecookie=" + cookieString + ";"]
let cookie = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url!)
cookieStorage.setCookies(cookie, for: url, mainDocumentURL: nil)
let urlRequest = URLRequest.init(url: url!)
theWebView.load(urlRequest)
However, when I use the Simulator and inspect it using Safari Develop, it states that I have no cookies set. Thoughts on what I screwed up on or that I failed to take into account?
Swift 3.0
Use the following line to set cookie for urlRequest:
urlRequest?.setValue("somecookie" + cookieString, forHTTPHeaderField: "Cookie")

swift3 webview with post request

I am running a school project and I am new from swift3.
By searching, I know how to pass a data from one view to anther:
Passing data from a tableview to webview
In the post above, he is using http get request to pass data to website, then reload the webivew:
let URL = NSURL(string: "https://www.example.com?data=\(passData)")
webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)
I see some useful links like about code with http post request in here:
HTTP Request in Swift with POST method. In a result, the code can print out the http response.
My question is that, how to implement a webview with sending a http post reuqest, like id, name, etc, instead of get method.
In anther words: I want to reload the webview(like example.com) and that website will contain the value I sent via http post request.
example.com:
$id = $_POST['id'];
echo $id;
Thanks.
Just create a URLRequest for POST as shown in the second link, and pass it to the webView:
var request = URLRequest(url: URL(string: "http://www.example.com/")!)
request.httpMethod = "POST"
let postString = "id=\(idString)"
request.httpBody = postString.data(using: .utf8)
webView.loadRequest(request) //if your `webView` is `UIWebView`
(Consider using WKWebView rather than UIWebView.)
You may need idString to be escaped if it contains some special characters.
By the way, the two line code:
let URL = NSURL(string: "https://www.example.com?data=\(passData)")
webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)
does not seem to be a good Swift 3 code. It can be written as:
let url = URL(string: "https://www.example.com?data=\(passData)")!
webView.loadRequest(URLRequest(url: url))

swift 3 urlRequest session.dataTask not firing

I am trying to get stock quotes from Yahoo using Swift 3. Although there are some decent tutorials on Swift 2, none of them seem to translate well to Swift 3.
The issue I have at the moment is that in the code below, the session.dataTask is never called. The print statement never fires and the rest of the code that is in there does not work.
I have checked that the request variable looks good, and the url has been tested on the yahoo developer site.
So I'm thinking I must have the syntax of the dataTask wrong or has an error so is skipping completely.
Any thoughts?
urlString = "http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN ('APL')"
//let urlNSS : NSString = urlString as NSString
let urlStr : String = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url : URL = URL(string: urlStr as String)!
let request = URLRequest(url: url)
let session = URLSession.shared
let config = URLSessionConfiguration.default
let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
print("in the task")
..
..
)}
task.resume()
If I inspect task I see the following
You must resume the task (task.resume()) that you have created. By default, a task is in suspended state.
I have created a Playground file with a different Yahoo RSS Feed URL. https://drive.google.com/file/d/0B5nqEBSJjCriWl9UTWcxSE42Yk0/view?usp=sharing
The URL you have in your question is not giving any data.
<error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:lang="en-US">
<description>No definition found for Table yahoo.finance.quotes</description>
</error>
Code as Below:
//: Playground - noun: a place where people can play
import UIKit
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var str = "Hello, playground"
let yahooURLString = "https://feeds.finance.yahoo.com/rss/2.0/headline?s=yhoo&region=US&lang=en-US"
let yahooRSSURL: URL = URL(string: yahooURLString)!
var request = URLRequest(url: yahooRSSURL)
request.httpMethod = "GET"
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let task = session.dataTask(with: request) {data, response, err in
print("Entered the completionHandler")
print("Response JSON:\n\(String(data: data!, encoding: String.Encoding.utf8)!)")
}
task.resume()
Hope this helps.
Edit: Attaching a screenshot of print statements appearing in the console of playgorund.