Issue retrieving http header -file path value - swift3

I'm trying to retrieve a custom header that is returned from an HTTP Get request. I'm able to retrieve all the other header values.
Alamofire.request(
apiURL,
parameters: ["UserID": post.userID]
)
.responseData { response in
guard response.result.isSuccess else {
print("Error while fetching Data: \(String(describing: response.result.error))")
return
}
if let headers = response.response?.allHeaderFields as? [String: String]{
if let myHeader = headers["profileImageURL"] as? String {
print(myHeader)
}
Using the developer tool in Chrome I can see the Header is being returned. Perhaps I'm casting incorrectly? The Header name is profileImageURL

The userID parameter that I was passing to the HTTP Get was incorrect.

Related

How to test the status code when key headers are valid

I wanted to test the status code if all the key headers are valid.
All I know is the Content-type key. I'm getting an error when doing this to other key headers.
var headers =pm.request.headers.toObject()
console.log(headers)
all headers send request can be accessed using above method in the test script
var headers = pm.request.headers.map()
console.log(headers.length)
_ = require("lodash")
let expectedHeaders = ["Accept","Content-Type"]
let requiredHeaders =_.filter(headers, function (n) {
return expectedHeaders.includes(n.key);
});
_.isEqual(requiredHeaders.map(n=>n.key).sort(), expectedHeaders.sort()) ? pm.test("sometest",function(){
pm.expect(pm.response.code).to.eql(200)
}):null
is here we are filtering out required headers and validating that all headers are present as expected and the running a test if the header is as expected else doing nothing

One request - Two responses. Which end is creating the problem (Front / Back)

Problem:
When I call a request from iOS swift based app, then the server is responding two responses.
Inputs:
In my request, am sending some user values including one base64 image string. I already ensure that my app is calling request only one time.
Outputs:
When we opened the server log, it printed two set of request and response. But, difference that the first one is not having base64 image string and second one is having it. Thats why am receiving two different responses.
Questions:
What end is causing this problem - Front / back end?
Note:
I given front code below but I can’t provide back end code.
let task = urlSession.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in
if error != nil
{
print("Error ==",error!.localizedDescription);
onFailure(error!.localizedDescription)
}
else
{
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
// For some critical cases:
//print("Status code: ", statusCode)
//print("http Response: ", httpResponse)
// JSON serialize
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print("Server Response == ",jsonResponse)
onSuccess(statusCode, jsonResponse)
}
catch
{
onFailure("JSON Parser Error")
}
}
})`

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))

Django oauth2 token request fails on Swift Alamofire

I am building both an iOS client and a django backend service. The connection made between the systems is OAUTH2, implemented by the django-oauth2-toolkit.
Although the following command done in curl works (returns an access token):
curl -X POST -d "grant_type=password&username=<user>&password=<password>" http://<clientID>:<clientSecret>#localhost:8000/o/token/
The following Swift snippet, that uses Alamofire, receives "invalid_client", as a response.
let request = "http://\(Authentication.clientId):\(Authentication.clientSecret)#localhost:8000/o/token/"
var URLRequest = NSMutableURLRequest(URL: NSURL(string: request)!)
URLRequest.HTTPMethod = "POST"
let parameters = ["grant_type": "password", "username": in_username.text!, "password": in_password.text!]
let encoding = Alamofire.ParameterEncoding.URL
(URLRequest, _) = encoding.encode(URLRequest, parameters: parameters)
URLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
Alamofire.request(URLRequest)
.responseJSON { response in
let data = response
print(data)
}
I then traced the InvalidClientError in the django-oauth2-toolkit source, and found that the exception was raised in the highlighted snippet of the following file:
oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py
if self.request_validator.client_authentication_required(request):
log.debug('Authenticating client, %r.', request)
print(request) # I included this print message to inspect the request variable in console.
if not self.request_validator.authenticate_client(request):
log.debug('Client authentication failed, %r.', request)
raise errors.InvalidClientError(request=request) # RAISED!
I included the print(request) line to inspect the differences between the request made by curl and by Alamofire. The major difference was that the curl version included an authorization key:
'Authorization': 'Basic Z3ZFSjVXejloUGgybUJmdDNRaGhXZnlhNHpETG5KY3V6djJldWMwcjpSbVNPMkpwRFQ4bHp1UVFDYXN3T3dvVFkzRTBia01YWWxHVHNMcG5JUGZCUHFjbHJSZE5EOXQzd3RCS2xwR09MNWs1bEE4S2hmRUkydEhvWmx3ZVRKZkFXUDM4OERZa1NTZ0RvS0p3WjUyejRSQ29WRkZBS01RS1lydEpsTWNXag=='
and the Alamofire request didn't.
I highly suspect this is the culprit, but I really don't know else to do though from here on. I would really appreciate any wisdom.
Found the answer!
Was reading through a RFC document on the HTTP protocol, when this section caught my eye.
https://www.rfc-editor.org/rfc/rfc1945#section-11.1
Specifically,
To receive authorization, the client sends the user-ID and password,
separated by a single colon (":") character, within a base64 [5]
encoded string in the credentials.
It seems that Alamofire does not encode in 64 bits the clientId and clientSecret, as expected. Obviously, curl does this automatically. So I did the following:
First encode:
static let clientData: NSData = "\(clientId):\(clientSecret)".dataUsingEncoding(NSUTF8StringEncoding)!
static let client64String = clientData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.init(rawValue: 0))
Then set the request header using the resulting value:
let request = "http://localhost:8000/o/token/"
var URLRequest = NSMutableURLRequest(URL: NSURL(string: request)!)
URLRequest.HTTPMethod = "POST"
let parameters = ["grant_type": "password",
"username": in_username.text!,
"password": in_password.text!,
]
let encoding = Alamofire.ParameterEncoding.URL
(URLRequest, _) = encoding.encode(URLRequest, parameters: parameters)
// SOLUTION!
URLRequest.setValue("Basic \(Authentication.client64String)", forHTTPHeaderField: "Authorization")
Alamofire.request(URLRequest)
.responseJSON { response in
let data = response
print(data)
}
I then received the expected token as a response.

Get facebook user's uploaded photos in swift/xcode 6

I've been able to login and get the first name, last name, email, and profile picture url in Xcode 6.1.1 with swift. I haven't been able to figure out how to get the urls or pull the images from a user, even though I have the user_photos Permission. Any help would be greatly appreciated.
You need to make request to graph api that will return you JSON in response to your request. For example if you want to get name, profile picture (it will give you url for profile picture) and id you can make request in your viewDidLoad() as follows
FBRequestConnection.startWithGraphPath("me?fields=id,name,picture", completionHandler: {(connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
if (result? != nil) {
NSLog("error = \(error)")
println(result)
}
} as FBRequestHandler)
to set a label text to facebook name you can use
var resultdict = result as? NSDictionary
if let name = resultdict?["name"] as? String {
self.YOUR_LABEL.text = name //name is response object in "result" dictionary
}
Cheers!!!