title: Instagram Login & Access Token - Swift
body: <p>I am trying to create an "Connect with Instagram" button that would allow me to get current user's Instagram id. Using these tutorials: <a href="https://vimeo.com/107295686" rel="nofollow">[1]</a> - <a href="https://vimeo.com/107319225" rel="nofollow">[2]</a>, I managed to do the same for Twitter however I couldn't convert it to Instagram. Here is my code:</p>
  
  <pre><code>  User.swift
   --------------
  import UIKit
  
  var _currentInstagramUser: InstagramUser?
  let currentInstagramUserKey = "kCurrentInstagramUserKey"
  
  class InstagramUser: NSObject {
  
  var instagramid: String?
  var instagramusername: String?
  var dictionary: NSDictionary
  
  init(dictionary: NSDictionary) {
      self.dictionary = dictionary
  
      instagramid = dictionary["id"] as? String
      instagramusername = dictionary["username"] as? String
  
  }
  
  class var currentInstagramUser: InstagramUser? {
      get {
      if _currentInstagramUser == nil {
      var data = NSUserDefaults.standardUserDefaults().objectForKey(currentInstagramUserKey) as? NSData
  
      if data != nil {
      var dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
      _currentInstagramUser = InstagramUser(dictionary: dictionary)
  
      }
  
      }
      return _currentInstagramUser
      }
      set(user) {
          _currentInstagramUser = user
          println(user)
  
          //SAVE USER TO DATABASE &amp;&amp;&amp; Remember User
          if _currentInstagramUser != nil {
              var data = NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: nil, error: nil)
              NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentInstagramUserKey)
              NSUserDefaults.standardUserDefaults().synchronize()
  
          } else {
              NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentInstagramUserKey)
          }
  
          NSUserDefaults.standardUserDefaults().synchronize()            
      }
  }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>  InstagramClient.swift
   -----------------------
    let instagramConsumerKey = "###"
    let instagramConsumerSecret = "###"
    let instagramBaseURL = NSURL(string: "https://api.instagram.com")
  
    class InstagramClient: BDBOAuth1RequestOperationManager {
  
  var instagramLoginCompletion: ((user: InstagramUser?, error: NSError?) -&gt; ())?
  
  class var SharedInstance: InstagramClient {
      struct Static {
          static let instance = InstagramClient(baseURL: instagramBaseURL, consumerKey: instagramConsumerKey, consumerSecret: instagramConsumerSecret)
      }
  
      return Static.instance
  }
  
  
  func loginWithCompletionForInstagram(completion: (user: InstagramUser?, error: NSError?) -&gt; ()) {
      instagramLoginCompletion = completion
  
      //Fetch Request Token &amp; Redirect Authorization Page of Twitter
      InstagramClient.SharedInstance.requestSerializer.removeAccessToken()
  
      InstagramClient.SharedInstance.fetchRequestTokenWithPath("oauth/access_token", method: "POST", callbackURL: NSURL(string: "tatchinsta://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -&gt; Void in
  
          println("Success")
  
          var authURL = NSURL(string: "https://instagram.com/oauth/authorize/?client_id="###"&amp;redirect_uri="###"&amp;response_type=\(requestToken.token)")
          UIApplication.sharedApplication().openURL(authURL!)
  
          }){ (error: NSError!) -&gt; Void in
  
              println(error)
              self.instagramLoginCompletion?(user: nil, error: error)
      }
  
  }
  
  func instagramOpenURL(url: NSURL) {
      fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuth1Credential(queryString: url.query) , success: { (accessToken: BDBOAuth1Credential!) -&gt; Void in
          println("got access token")
          InstagramClient.SharedInstance.requestSerializer.saveAccessToken(accessToken)
  
          InstagramClient.SharedInstance.GET("https://api.instagram.com/v1/users/self/?access_token=ACCESS-TOKEN", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response:AnyObject!) -&gt; Void in
  
              println("user: \(response)")
              var user = InstagramUser(dictionary: response as! NSDictionary)
              InstagramUser.currentInstagramUser = user
  
              self.instagramLoginCompletion?(user: user, error: nil)
  
              }, failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -&gt; Void in
                  println("error")
                  self.instagramLoginCompletion?(user: nil, error: error)
          })
  
          }) { (error: NSError!) -&gt; Void in
              println("Failed to receive access token")
              self.instagramLoginCompletion?(user: nil, error: error)
      }   
  }    
  }
  </code></pre>
  
  <hr>
  
  <pre><code>    AppDelegate.swift
      ------------------
      func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -&gt; Bool {
      InstagramClient.SharedInstance.instagramOpenURL(url)
      return true
  }
  </code></pre>
  
  <hr>
  
  <pre><code>    ViewController.swift
      --------------------
      import UIKit
  
  
  class ViewController: UIViewController {
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
  }
  
   @IBAction func instagramLoginButton(sender: AnyObject) {
  
      InstagramClient.SharedInstance.loginWithCompletionForInstagram() {
          (user: InstagramUser?, error: NSError?) in
          if user != nil {
              //user exists
          } else {
              //login error
          }
  
      }
  
  }
  </code></pre>
  
  <hr>
  
  <p>When I click on the "Login with Instagram" button (so loginWithCompletionForInstagram) function, the <strong>error log</strong> I receive is:</p>
  
  <pre><code>Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7f96bb900150 {com.alamofire.serialization.response.error.response=&lt;NSHTTPURLResponse: 0x7f96b9442ed0&gt; { URL: https://api.instagram.com/oauth/access_token } { status code: 400, headers {
  "Cache-Control" = "private, no-cache, no-store, must-revalidate";
  Connection = "keep-alive";
  "Content-Language" = en;
  "Content-Length" = 94;
  "Content-Type" = "application/json";
  Date = "Fri, 24 Apr 2015 23:55:20 GMT";
  Expires = "Sat, 01 Jan 2000 00:00:00 GMT";
  Pragma = "no-cache";
  Server = nginx;
  "Set-Cookie" = "csrftoken=f021070d367caacba3c1c63b38ac9394; expires=Fri, 22-Apr-2016 23:55:20 GMT; Max-Age=31449600; Path=/, mid=VTrX6AAAAAHQfPFksK-b-EDV7C0t; expires=Thu, 19-Apr-2035 23:55:20 GMT; Max-Age=630720000; Path=/";
  Vary = "Cookie, Accept-Language";
    } }, NSErrorFailingURLKey=https://api.instagram.com/oauth/access_token, com.alamofire.serialization.response.error.data=&lt;7b22636f 6465223a 20343030 2c202265 72726f72 5f747970 65223a20 224f4175 74684578 63657074 696f6e22 2c202265 72726f72 5f6d6573 73616765 223a2022 596f7520 6d757374 2070726f 76696465 20612063 6c69656e 745f6964 227d&gt;, NSLocalizedDescription=Request failed: bad request (400)}
  </code></pre>