func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
// Set the POST parameters.
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(String(describing: redirectURL))&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
let postData = postParams.data(using: String.Encoding.utf8)
let request = NSMutableURLRequest(url: NSURL(string: accessTokenEndPoint)! as URL)
request.httpMethod = "POST"
//http body
request.httpBody = postData
//headerfield
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// init the session
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
// Throwing and error it needs a URLRequest at session.dataTask("Here")
// Below is the error Xcode yells
// Ambiguous reference to member 'dataTask(with:completionHandler:)
}
}
Asked
Active
Viewed 5,743 times
1

rmaddy
- 314,917
- 42
- 532
- 579

BigArmsWriteSmallCode
- 35
- 1
- 9
-
4`NSURL(string: accessTokenEndPoint)! as URL`: You seem to know how to cast. But clearly, don't use `NSMutableURLRequet`. In Swift 3+, when available avoid NSStuff, use the Swift one without NS when available: NSURL => URL, NS(Mutable)URLRequest => URLRequest. – Larme Jul 23 '18 at 05:38
3 Answers
3
Few points I would like to add :
1. Unwrap optional properly, use if-let/guard-let
.
2. NS is most of the time from Objective-C, so remove NS and it's swift (most of the times)
func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(String(describing: redirectURL))&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
guard let url = URL(string: accessTokenEndPoint) else {
return
}
let postData = postParams.data(using: .utf8) // Suggested by rmaddy
var request = URLRequest(url: url)
//let request = NSMutableURLRequest(url: NSURL(string: accessTokenEndPoint)! as URL)
request.httpMethod = "POST"
request.httpBody = postData
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
}
task.resume()
}

Sharad Chauhan
- 4,821
- 2
- 25
- 50
-
1The force unwrapping is perfectly fine in this case, this (hard-coded) URL cannot be `nil` – vadian Jul 23 '18 at 06:30
1
You can create http body with this function:
private let linkedInKey = ""
private let linkedInSecret = ""
func postBody(authorizationCode: String) -> String {
let grantType = "authorization_code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth"
return [
"grant_type":grantType,
"code":authorizationCode,
"redirect_uri":redirectURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed),
"client_id":linkedInKey,
"client_secret":linkedInSecret
].enumerated().compactMap {
if let valueForKey = $1.value {
return $1.key + "=" + valueForKey
}
return nil
}.joined(separator: "&")
}
And now the function requestForAccessToken(authorizationCode:)
will be shorter:
func requestForAccessToken(authorizationCode: String) {
if var urlComponents = URLComponents(string: "https://com.appcoda.linkedin.oauth") {
urlComponents.path = "/oauth"
if let urlComponentsURL = urlComponents.url {
var request = URLRequest(url: urlComponentsURL)
request.httpMethod = "POST"
request.httpBody = self.postBody(authorizationCode: authorizationCode).data(using: .utf8)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
}
task.resume()
}
}
}

Roman Podymov
- 4,168
- 4
- 30
- 57
0
use as below
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest ) { (data, response, error) in
}

ManuRaphy
- 361
- 1
- 13