How to refresh UIWebView images - ios

I went through a few SO post and can't seem to fix my issues.
The codes works fine, but if i update my profile pics, the UIWebView, will still show the cached image instead of the updated image.
if i close my app and reopen, the webview will update to the new image.
any pointer are greatly appreciated.
func getLeaderBoard()
{
leaderWebView.loadRequest(getStaticWebView(urlStr: getLeaderBoardUrl) as URLRequest)
}
func getStaticWebView(urlStr:String) -> NSMutableURLRequest
{
let url = URL.init(string: urlStr)
let request = NSMutableURLRequest.init(url: url!)
request.httpMethod = "GET"
request.setValue("token \(kToken)", forHTTPHeaderField: "Authorization")
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
return request
}

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/

iOS Swift WKWebView login with Session

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)

sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code?

I'm using XCode 7.3. Here is my code:
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in}}
This works fine and my php-Script gets the string it should. But there is the
sendAsynchronousRequest was deprecated in iOS 9
message.
As I read, with Swift 2 the method has changed.
I searched a lot for this error, but I'm not able to convert the code that it matches to Swift 2. As I also read, i should use something like this
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)
but I can't get it down. And actually, I don't understand every single line. I wrote the code myself, but from some examples that it works for me.
This is the most basic way you'd use a shared session:
if let url = NSURL(string: "http://mytesturl.com"),
userField = UserTextField.text {
let request = NSMutableURLRequest(URL: url)
let bodyData = "data=" + userField
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
}
)
dataTask.resume()
}
For more detail on the other approaches including background and ephemeral sessions, as well as how to handle the NUSRLResponse, see my blogpost.
As you've found out NSURLConnection has been deprecated and NSURLSession is the new shiny.
For your example to work you still need to use the NSURL and the NSURLRequest that you have already created, and then you need an NSURLSession which you can use in various ways.
I can see that you already use the callback so in your case I assume it would be
session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
and then the important thing to remember is to call resume() on your task.
So...to translate your code I'm thinking something along those lines
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.defaultSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
task.resume()
}
You can read more about NSURL session in this tutorial from raywenderlich.com
Hope that helps

NSURLRequest produce different result than HTTP proxy client

I send the same HTTP message from a HTTP proxy client and with NSURLRequest + NSURLConnection, and get back different result. It is an authentication request. From HTTP proxy authentication request is accepted, sending from app not. Why? Accepted means after redirection HTML will contains no Oops substring.
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let email2 = (viewController!.email.text as NSString).stringByReplacingOccurrencesOfString("#", withString: "%40")
let str = "name=\(email2)&pass=\(viewController!.password.text)&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d2 = d {
request.HTTPBody = d2
let urlConnection = NSURLConnection(request: request, delegate: self)
}
UPDATE
I have put #teamnorge's code below into playground and into an empty Single View Application project. Returned HTML in project contains the Oops substring, code used in playground not containes it, any idea what is going on, why same request produce different HTML result? I get failed message also from iOS device and from simulator too.
UPDATE
Removed NSURLRequest cache like here recommended, but still not works as expected. And here.
UPDATE
Tried to remove all the credentials like here, but didn't help, no credential was found.
It looks like when you receive HTTP 302 and new Location URL, iOS does automatically fetch the page by this URL, so I guess your response is in fact the HTML content of the redirection page. Please verify.
UPDATE:
import UIKit
import XCPlayground
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url!)
let str = "name=kukodajanos%40icloud.com&pass=jelszo&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = d
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
if contents!.rangeOfString("Oops").length == 0 {
println("success")
} else {
println("failed")
}
} else {
println(error.localizedDescription)
}
}
XCPSetExecutionShouldContinueIndefinitely()

Alamofire loading from cache even when cache policy set to ReloadIgnoringLocalAndRemoteCacheData

I set cache policy to request in Alamofire to ignore local cache.
Then I load a viewcontroller with network connection, then I disconnect network connection, kill the app and run it again.
Now no network available error is not shown(ie alamofire doesnt create nserror object) created, instead app runs as if the request succeeded getting data from cache obviously.And the odd thing is the when I tried to inspect the cached data using
NSURLCache.sharedURLCache().cachedResponseForRequest(request)
nil is returned eventhough the data was from cache ..
The only way I could prevent cached responses is perform NSURLCache.sharedURLCache().removeAllCachedResponses()
let request = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 100)
Alamofire.manager.request(method, request, parameters:params)
.responseJSON { (request, response, data, error) in
if let anError = error {
if anError.code == NSURLErrorNotConnectedToInternet {
UIAlertView(title: "Alert", message: "No Network Connection Available", delegate: nil, cancelButtonTitle: "ok").show()
}
} else if let data: AnyObject = data {
println(NSURLCache.sharedURLCache().cachedResponseForRequest(request))
//prints nil
}
}
}
What I want to do is load data from cache only if network connection is not available, something like limited offline mode.How to do this?
I'm using this way in a project and it's working:
let mutableURLRequest = NSMutableURLRequest(URL: SERVICEURL)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.HTTPBody = self.createJson()
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request(mutableURLRequest).validate().responseJSON{ response in...
Hope it helps.
Thanks to #FábioSalata I solved my problem like this.
var req = URLRequest(url: URL(string: "<URL>")!)
req.httpMethod = "GET"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("<Auth KEY>", forHTTPHeaderField:"Authorization" )
req.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
Alamofire.request(req).validate().responseJSON { response in ...
ReloadIgnoringLocalAndRemoteCacheData is not implemented.
https://developer.apple.com/reference/foundation/nsurlrequestcachepolicy/1408722-reloadignoringlocalandremotecach
http://nshipster.com/nsurlcache/
Update: Starting with iOS 13, NSURLRequest.CachePolicy.reloadRevalidatingCacheData and NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData are implemented. https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes

Resources