iOS Swift WKWebView login with Session - ios

I come from UIWebView where I had following code:
let url2 = NSURL(string: URL+"/auth?id="+self.username!+"&pw="+self.password!)
let task2 = NSURLSession.sharedSession().dataTaskWithURL(url2!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
task2.resume()
Doing this I was automatically logged in.
But now with the WKWebView this is not working anymore.
The Code is executed just before loading the request:
self.webView = WKWebView()
let request = NSURLRequest(URL: portalURL!)
self.webView!.loadRequest(request)
Username and Password are stored on the Device, when the User installs the Application.
How can I get a similar effect with WKWebView?

You'd better add user info to request header. Like this:
let url = NSURL(string: urlString)
let urlRequest = NSMutableURLRequest(URL: url!)
if needAddHttpHeader {
urlRequest.addValue("login", forHTTPHeaderField: "User-Login")
urlRequest.addValue("token", forHTTPHeaderField: "User-Token")
UBLog(urlRequest)
}
webView.loadRequest(urlRequest)

Related

Swift - urlsession cookies

I have a php webAPI which works well and I want to login with that in my app. I want to use cookies for that. So, I save the cookies when the user signs in and that works. I store it in userdefaults when I want to use only place cookies into HTTPCookieStorage.shared.
I try to use this for my new request, and my question is how can I add the cookies to my request?
I tried this but it's not working...
let cookiesArray = HTTPCookieStorage.shared.cookies
print(cookiesArray)
//HTTPCookieStorage.shared.setCookies(cookiesArray!, for: url, mainDocumentURL: url)
let headers = HTTPCookie.requestHeaderFields(with: cookiesArray!)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpShouldHandleCookies = true
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
urlRequest.allHTTPHeaderFields = headers
//urlRequest.setValue("PHPSESSID=oe22uf92poc5c7s23u4ukl83g0", forHTTPHeaderField: "Cookie")
//URLSessionConfiguration().httpCookieAcceptPolicy = .always
let session = URLSession.shared
session.configuration.httpCookieStorage = HTTPCookieStorage.shared
session.configuration.httpCookieAcceptPolicy = .always
session.configuration.httpShouldSetCookies = true
session.configuration.httpAdditionalHeaders = headers
let task = session.dataTask(with: urlRequest) { (data, response, error) in
print(data)
print(response)
print(error)
print("itt az end\n")
}
task.resume()
I can't comment yet, but I agree that more info is needed. If you are getting errors those would be helpful to post. Also, what you are getting for your
data
response
error
would be helpful.
Other than that, I would first look at setting up Charles as an HTTP Proxy so you can see exactly what is happening when you make the request. Knowing what response you are receiving will let you know what is going wrong.
https://www.charlesproxy.com/

Swift: NSURL Session not working with watchOS

I'am using a NSURL Session to get the HTML code of a specific website. The following code works perfectly fine with iOS (in ViewController.swift) but it always fails in watchOS (in InterfaceController.swift). The code always print the else statement: print("apple watch: error with loading nsurlsession").
Could anybody explain me (why it fails and) how I could change this? I'm grateful for every response!
(I'm using swift 4.0 with iOS 11 and watchOS 4.0 - tested in simulator and on iPhone 7 with paired Apple Watch series 2)
Code:
func authorizeBase() {
let loginString = NSString(format: "%#:%#", username, password)
let loginData: NSData = loginString.data(using: String.Encoding.utf8.rawValue)! as NSData
let base64LoginString = loginData.base64EncodedString(options: [])
let url: NSURL = NSURL(string: urlPath)!
let request: NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData //deactivate cache
config.urlCache = nil
let authString = "Basic \(base64LoginString)"
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)
session.dataTask(with: url as URL) {
( data, response, error) in
if (response as? HTTPURLResponse) != nil {
_ = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let contents = String(data: data!, encoding: .ascii)
print("apple watch: Content:", contents!)
self.parseHTMLOverview(content: contents!)
self.updateTable() //!!!
}
else {
print("apple watch: error with loading nsurlsession")
}
}.resume()
}
Thank's a lot for your hint Srstka!
After hours of thinking I figured it out. I just forgot to add "Allow Arbitrary Loads" to the Info.plist in the WatchKit Extension.

URLSession is not getting timeout after specified interval in swift 3 on iOS 10

I am trying to hit a Json request in swift3 through urlsession. Request is not getting timeout after 10s
let request = NSMutableURLRequest(url: NSURL(string:url )! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0 )
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = RequestBody
let configuration =
URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10
configuration.timeoutIntervalForResource = 10
let session = URLSession(configuration: configuration, delegate: self as? URLSessionDelegate, delegateQueue:OperationQueue.main)
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in...
}
The issue is you never actually start the network request.
You need to call dataTask.resume() to actually start the request. This needs to happen right after the closure, see code below:
guard let url = URL(string: urlString) else { return }
let request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0 )
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = RequestBody
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in...
}
dataTask.resume()

Making a simple HTTPS POST request with params in Swift

I cannot for the life of me figure out this problem. And I hope you guys can.
I want to send a username and a password over a HTTPS POST. Problem is, I cannot make it work.
The code I am trying to make work right now is:
import UIKit
import Foundation
import PlaygroundSupport
let url:URL = URL(string: "https://mywebsite.com/myAPI")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "username=Pleasework&password=itwont"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "Got nothing")
}
task.resume()
Looking at my server logs, this request goes through, but it is supposed to create a file containing said params. I tried using a Chrome extension called "Request Maker", and the file was created. (The file is created with PHP, and is irrelevant to this question)I found that the file was only created once the content type was specified, so I tried that in Swift.
I am using Swift 3 and Xcode 8, I hope you guys can help me send a simple post request with a content type to a URL, all of the other answers on Stackoverflow have not helped me.
Thanks

Making HTTP Request with header in Swift

I am trying to make an HTTP request to the Imgur API. I am trying to retrieve all images associated with the tag "cats." The url, according to the Imgur API is: https://api.imgur.com/3/gallery/t/cats
the Imgur API states the following about the authorization needed to make get requests:
For public read-only and anonymous resources, such as getting image
info, looking up user comments, etc. all you need to do is send an
authorization header with your client_id in your requests. This also
works if you'd like to upload images anonymously (without the image
being tied to an account), or if you'd like to create an anonymous
album. This lets us know which application is accessing the API.
Authorization: Client-ID YOUR_CLIENT_ID
I've looked at the following questions and tried things suggested there, but none of them have helped.
JSON NSURLRequest with credentials
Swift GET request with parameters
How to make a Http get and set httpHeader in Swift?
My current code is this:
let string = "https://api.imgur.com/3/gallery/t/cats"
let url = NSURL(string: string)
let request = NSMutableURLRequest(URL: url!)
request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
//request.addValue("clientIDhere", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let antwort = response as? NSHTTPURLResponse {
let code = antwort.statusCode
print(code)
}
}
tache.resume()
But I continually get a status code of 403, meaning authorization is required. What am I doing wrong?
I think you need to prepend Client-ID string to your actual client ID as for the header value:
request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")
Updated for swift 4 :
func fetchPhotoRequest(YOUR_CLIENT_ID: String) {
let string = "https://photoslibrary.googleapis.com/v1/albums"
let url = NSURL(string: string)
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(YOUR_CLIENT_ID, forHTTPHeaderField: "Authorization") //**
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let res = response as? HTTPURLResponse {
print("res: \(String(describing: res))")
print("Response: \(String(describing: response))")
}else{
print("Error: \(String(describing: error))")
}
}
mData.resume()
}

Resources