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/
Related
I want to open an url in the background to update my database with information,
but it should not open safari because customer shouldn't be able to see the php link.
would be glad for any help,
i just need help to open the URL in the background
I believe what you're looking for is an HTTP request. This is what browsers do to get content from a webpage. There are many ways to do an HTTP request to a url in iOS. One such way is with the URLSession class.
let url = URL(string: "http://www.google.com/") //Or your URL
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = "Data to send to your backend".data(using: .utf8)!
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
//There was an error
} else {
//The HTTP request was successful
print(String(data: data!, encoding: .utf8)!)
}
}
task.resume()
This will send the data in the httpBody property to your backend in a HTTP request.
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
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)
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()
}
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