Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ViewController: UIViewController {
- var urlSession = URLSession(configuration: .default)
- override func viewDidLoad() {
- super.viewDidLoad()
- authorize(withCode: "REMOVED") { (error) in
- print(error)
- }
- }
- func buildURL(appendingPath: String, withGetParameters: [String: String]) -> URL {
- var items = Array<URLQueryItem>()
- var components = URLComponents(string: appendingPath)!
- for key in withGetParameters {
- let queryItem = URLQueryItem(name: key.0, value: key.1)
- items.append(queryItem)
- }
- components.queryItems = items;
- return components.url!
- }
- func buildPOSTTask(onURLSession urlSession: URLSession, appendingPath path: String, withPostParameters postParams: [String : String]?, getParameters getParams: [String : String]?, httpHeaders: [String : String]?, completionHandler completion: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionUploadTask {
- let fullURL: URL
- if let gets = getParams {
- fullURL = buildURL(appendingPath: "https://anilist.co/api/" + path, withGetParameters: gets)
- }
- else {
- fullURL = URL(string: path, relativeTo: URL(string: "https://anilist.co/api")!)!
- }
- var request = URLRequest(url: fullURL)
- request.httpMethod = "POST"
- var postParameters: Data? = nil
- if let posts = postParams {
- do {
- postParameters = try JSONSerialization.data(withJSONObject: posts, options: [])
- } catch let error as NSError {
- fatalError("[\(#function) \(#line)]: Could not build POST task: \(error.localizedDescription)")
- }
- }
- return urlSession.uploadTask(with: request, from: postParameters, completionHandler: completion)
- }
- func authorize(withCode code: String?, completion: (NSError?) -> Void) {
- let body: [String: String] = ["client_secret": "REMOVED",
- "grant_type": "authorization_code",
- "redirect_uri": "genericwebsitethatshouldntexist.bo",
- "client_id": "ibanez-hod6w",
- "code": code ?? "REMOVED"];
- let obtainTokenTask = buildPOSTTask(onURLSession: self.urlSession, appendingPath: "auth/access_token", withPostParameters: nil, getParameters: body, httpHeaders: nil) { (data, response, error) in
- if let err = error {
- completion(err)
- } else {
- print("Response is \(response)")
- completion(nil)
- }
- }
- obtainTokenTask.resume()
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement