
Instagram Private API Swift
Por favor, observe que SwiftyInsta não é mais mantido ativamente.
Consulte #244 para mais informações.
Confira Swiftagram se você procura alternativas atualizadas.
O Instagram oferece dois tipos de APIs para desenvolvedores. A Instagram API Platform (extremamente limitada em funcionalidade e próxima de ser descontinuada) e a Instagram Graph API apenas para contas Business e Creator.
No entanto, os aplicativos do Instagram dependem de um terceiro tipo de API, a chamada Private API ou API não oficial, e o SwiftyInsta é um cliente para iOS, macOS, tvOS e watchOS para elas, escrito inteiramente em Swift. Você pode tentar criar uma melhor experiência do Instagram para seus usuários, ou escrever bots para automatizar diferentes tarefas.
Essas APIs privadas não exigem token ou registro de aplicativo, mas não são autorizadas pelo Instagram para uso externo. Use por sua conta e risco.
File/Swift Packages/Add Package Dependency… no menu.https://github.com/TheM4hd1/SwiftyInsta.git.CocoaPods é um gerenciador de dependências para projetos Cocoa. Você pode instalá-lo com o seguinte comando:
$ gem install cocoapods
Para integrar o SwiftyInsta no seu projeto Xcode usando CocoaPods, especifique-o no seu Podfile:
use_frameworks!
target '<Your Target Name>' do
pod 'SwiftyInsta', '~> 2.0'
end
Então, execute o seguinte comando:
$ pod install
O SwiftyInsta depende de CryptoSwift e keychain-swift.
Credentials// these need to be strong references.
self.credentials = Credentials(username: /* username */, password: /* password */, verifyBy: .text)
self.handler = APIHandler()
handler.authenticate(with: .user(credentials)) {
switch $0 {
case .success(let response, _):
print("Login successful.")
// persist cache safely in the keychain for logging in again in the future.
guard let key = response.persist() else { return print("`Authentication.Response` could not be persisted.") }
// store the `key` wherever you want, so you can access the `Authentication.Response` later.
// `UserDefaults` is just an example.
UserDefaults.standard.set(key, forKey: "current.account")
UserDefaults.standard.synchronize()
case .failure(let error):
if error.requiresInstagramCode {
/* update interface to ask for code */
} else {
/* notify the user */
}
}
}
Assim que o usuário digitar o código de autenticação de dois fatores ou o código de desafio, simplesmente faça
self.credentials.code = /* the code */
E o completionHandler no authenticate(with: completionHandler:) anterior capturará automaticamente a resposta.
LoginWebViewControllerlet login = LoginWebViewController { controller, result in
controller.dismiss(animated: true, completion: nil)
// deal with authentication response.
guard let (response, _) = try? result.get() else { return print("Login failed.") }
print("Login successful.")
// persist cache safely in the keychain for logging in again in the future.
guard let key = response.persist() else { return print("`Authentication.Response` could not be persisted.") }
// store the `key` wherever you want, so you can access the `Authentication.Response` later.
// `UserDefaults` is just an example.
UserDefaults.standard.set(key, forKey: "current.account")
UserDefaults.standard.synchronize()
}
if #available(iOS 13, *) {
present(login, animated: true, completion: nil) // just swipe down to dismiss.
} else {
present(UINavigationController(rootViewController: login), // already adds a `Cancel` button to dismiss it.
animated: true,
completion: nil)
}
Ou implemente seu próprio UIViewController customizado usando LoginWebView e passe-o para um método authenticate do APIHandler usando .webView(/* your login web view */).
Authentication.ResponseSe você já persistiu um Authentication.Response de um usuário:
// recover the `key` returned by `Authentication.Response.persist()`.
// in our example, we stored it in `UserDefaults`.
guard let key = UserDefaults.standard.string(forKey: "current.account") else { return print("`key` not found.") }
// recover the safely persisted `Authentication.Response`.
guard let cache = Authentication.Response.persisted(with: key) else { return print("`Authentication.Response` not found.") }
// log in.
let handler = APIHandler()
handler.authenticate(with: .cache(cache)) { _ in
/* do something here */
}
Todos os endpoints são facilmente acessíveis a partir da sua instância APIHandler.
let handler: APIHandler = /* a valid, authenticated handler */
// for instance you can…
// …fetch your inbox.
handler.messages.inbox(with: .init(maxPagesToLoad: .max),
updateHandler: nil,
completionHandler: { _, _ in /* do something */ })
// …fetch all your followers.
handler.users.following(user: .me,
with: .init(maxPagesToLoad: .max),
updateHandler: nil,
completionHandler: { _, _ in /* do something */ })
Além disso, as respostas agora exibem cada valor contido no arquivo JSON retornado pela API: basta acessar qualquer rawResponse do ParsedResponse e começar a navegar, ou ficar com os acessórios sugeridos (ex.: username, name, etc. do User e aspectRatio, takenAt, content, etc. do Media).
Pull requests e issues são mais que bem-vindos.
1.* mantenedor2.* mantenedorEstamos ativamente procurando mantenedores.
Consulte #244 para mais informações.
SwiftyInsta está licenciado sob a licença MIT. Veja LICENSE para mais informações.