Skip to content

Instantly share code, notes, and snippets.

@shakked
Created January 24, 2016 17:26
Show Gist options
  • Save shakked/944deda3db6e9142f624 to your computer and use it in GitHub Desktop.
Save shakked/944deda3db6e9142f624 to your computer and use it in GitHub Desktop.
import UIKit
import AFNetworking
class InstagramQuerier: NSObject {
static let sharedQuerier = InstagramQuerier()
private let manager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
func fetchFollowers(account: Account, count: Int = -1, completion: (Bool, [User]) -> (Void)) {
let params = "/users/\(account.userId)/followed-by|access_token=\(account.accessToken)"
let sig = HMAC.signWithKey(UserSettings.InstagramClientSecret(), usingData: params)
let parameters = [
"access_token" : account.accessToken,
"sig" : sig
]
let urlString = "https://api.instagram.com/v1/users/\(account.userId)/followed-by/"
manager.GET(urlString, parameters: parameters, success: { (operation, result) -> Void in
let result = result as! NSDictionary
let pagination = result["pagination"] as! NSDictionary
let nextURLString = pagination["next_url"] as? String
let usersInfo = result["data"] as! NSArray
let currentFollowers = User.parse(usersInfo)
self.followersHelper(count, currentFollowers: currentFollowers, nextURLString: nextURLString, completion: completion)
}) { (operation, error) -> Void in
completion(false, [])
}
}
private func followersHelper(count: Int, currentFollowers: [User], nextURLString: String?, completion: (Bool, [User]) -> (Void)) {
if let nextURLString = nextURLString {
let nextURL = NSURL(string: nextURLString)!
let queryStrings = nextURL.parameters()
let accessToken = queryStrings["access_token"]!
let cursor = queryStrings["cursor"]!
let userId = nextURL.pathComponents![3]
let params = "/users/\(userId)/followed-by|access_token=\(accessToken)|cursor=\(cursor)"
let sig = HMAC.signWithKey(UserSettings.InstagramClientSecret(), usingData: params)
let parameters = [
"access_token" : accessToken,
"cursor" : cursor,
"sig" : sig
]
manager.GET("https://api.instagram.com/v1/users/\(userId)/followed-by/", parameters: parameters, success: { (operation, result) -> Void in
let result = result as! NSDictionary
let pagination = result["pagination"] as! NSDictionary
let nextURLString = pagination["next_url"] as? String
let usersInfo = result["data"] as! NSArray
let users = User.parse(usersInfo)
let currentFollowers = currentFollowers + users
if currentFollowers.count >= count && count != -1 {
completion(true, currentFollowers)
} else {
self.followersHelper(count, currentFollowers: currentFollowers, nextURLString: nextURLString, completion: completion)
}
}) { (operation, error) -> Void in
}
} else {
completion(true, currentFollowers)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment