Comments (33)
Yeah it worked. Grazie mille π―
Next, i'll try to handle multiple account, it'll probably work. i'll keep here updated.
from swiftyinsta.
@mkeshnoda
If you succeeded with implementing multiple accounts, please add a note here for others, to prevent re-opening this issue in future.
And make sure to close issue after that.
Regards.
from swiftyinsta.
Edit: Finally managed to add second account. What i am trying to do haven't completed yet. I'll keep here updated and will tell how i did it.
Still not working... (Haven't tried it with Siwa yet because looks like it's not about login function)
By the way the other problem is :
After login, it fetches cookies like ds_user_id and csrfToken BUT it doesn't pass it to self.isUserLoggedIn(instagramCookies: instagramCookies!)
sometimes. And i don't have any idea why is it happening.
private func login() {
self.fetchCookies(completion: { (cookies) in
if let cookies = cookies {
for i in 0..<cookies.count {
let cookie = cookies[i]
}
}
let instagramCookies = cookies?.getInstagramCookies()
self.isUserLoggedIn(instagramCookies: instagramCookies!)
})
}
from swiftyinsta.
You should not use isUserLoggedIn(instagramCookies:)
, I left it public
just because it used to, but it's not supposed to be called like that. We should definitely push an update to mark it internal
or private
, to prevent confusion.
You need to pass the SessionCache
in the response directly to handler.login(cache:)
.
@mkeshnoda
from swiftyinsta.
I'm working next on "updating" (most likely just removing) the singleton interface (all the .shared
static
properties), in order to make more instances of APIHandler
(et alia) run in parallel with different users logged in at the same time.
It shouldn't take too long. I hope I can start working on it tomorrow, and if so it should definitely be done by Monday.
So more multi-users stuff coming soon π
@mkeshnoda
from swiftyinsta.
Just completed it. Yeah it worked. Thank you so much guys. @sbertix @TheM4hd1
from swiftyinsta.
Let's start from beginning.
- Login to
first account
- save cookies to your
database
for currentuserPk
orusername
- Add
new account
but before login, make sure toclean cookies
(and for caution, re-create handler again)
HTTPCookieStorage.shared.cookies?.forEach({ (cookie) in
HTTPCookieStorage.shared.deleteCookie(cookie)
})
Login
and runstep 2
again- whenever you wanted to
switch
betweenaccounts
you shouldclear cookies
again and pass thecookie
tohandler.login(cache: SessionCache)
These steps should help you, although I never tried to add multiple accounts by myself.
Note: Never save cookies (important data) to userDefaults
because of security reasons.
from swiftyinsta.
I am doing the same but when i tap on login button to login 2nd user it still returns first user's cookies. I delete cookies but it doesn't change a thing.
I tried something with desktop google chrome today. let me explain
I logged out from my account + i deleted all cookies. But when i refreshed instagram my account was still standing there. Maybe that's what's happening to me when i am trying to login with the second account.
from swiftyinsta.
Attach the codes here, so we can work on it and find the issue.
from swiftyinsta.
These are the code in general. I delete cookies many times before loginin the other account π’ but still, when i am trying to login it returns the old cookies.
By the way it returned new account's cookies 1-2 times but it doesn't login. Idk why.
Okay, when i want to add account :
let loginVC = LoginVC() self.navigationController?.pushViewController(loginVC, animated: true) loginVC.webView.deleteAllCookies()
Inside LoginVC i have var webView = InstagramLoginWebView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad() webView.loadInstagramLogin(isNeedPreloadForCookieSync: false)
webView.loginDelegate = self
}
Inside WebView
@objc func deleteAllCookies() {
print("deleting all cookies")
self.cleanEveryThing()
fetchCookies { (cookies) in
for cookie in cookies! {
self.delete(cookie: cookie)
}
}
}
private func login() {
self.fetchCookies(completion: { (cookies) in
if let cookies = cookies {
for i in 0..<cookies.count {
let cookie = cookies[i]
}
}
let instagramCookies = cookies?.getInstagramCookies()
self.isUserLoggedIn(instagramCookies: instagramCookies!)
})
}
public func isUserLoggedIn(instagramCookies : [HTTPCookie]) {
var isLogged = false
var csrfToken = ""
for i in 0..<instagramCookies.count {
let cookie = instagramCookies[i]
if cookie.name == "ds_user_id" {
isLogged = true
}
if cookie.name == "csrftoken" {
csrfToken = cookie.value
}
}
if isLogged {
let _urlSession = URLSession(configuration: .default)
let user = SessionStorage.create(username: "username", password: "password")
let instagramHandler = try! APIBuilder()
.createBuilder()
.setHttpHandler(urlSession: _urlSession)
.setRequestDelay(delay: .default)
.setUser(user: user)
.build()
let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (HTTPCookieStorage.shared.cookies?.getInstagramCookies()?.toCookieData())!, isUserAuthenticated: true)
let cookieler = (HTTPCookieStorage.shared.cookies?.getInstagramCookies())!
for i in 0..<cookieler.count {
let cookie = cookieler[i]
}
try? instagramHandler.login(cache: sessionCache, completion: { (result) in })
if self.loginDelegate != nil {
self.loginDelegate?.userLoggedSuccessfully()
}
InstaEndPoint.sharedInstance.handler = instagramHandler
self.getUser(handler: instagramHandler, csrfToken: csrfToken)
} else { //user didn't logged in
}
}
func storeCookies(forKeyUserPk: String) {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
var cookieDict = [String : AnyObject]()
for cookie in cookiesStorage.cookies(for: try! URLs.getInstagramCookieUrl())! {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
userDefaults.set(cookieDict, forKey: forKeyUserPk)
userDefaults.synchronize()
}
func restoreCookies(forKeyUserPk: String) {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
if let cookieDictionary = userDefaults.dictionary(forKey: forKeyUserPk) {
for (_, cookieProperties) in cookieDictionary {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
self.set(cookie: cookie)
cookiesStorage.setCookie(cookie)
}
}
}
}
from swiftyinsta.
Every time you call loadInstagramLogin
function, cookie deleting handled automatically. so you don't need to call it.
set isNeedPreloadForCookieSync = true
and every time you want to show webView
do something like this:
self.loginWebView = nil
self.loginWebView = InstagramLoginWebView(frame: CGRect.zero)
self.view.addSubview(self.loginWebView!)
// setup constraints
self.loginWebView?.loginDelegate = self
self.loginWebView?.loadInstagramLogin(isNeedPreloadForCookieSync: true)
If it doesn't help, try to use Siwa
framework for login for now. and I will double check the web issue.
Tell me if it works.
from swiftyinsta.
SwiftyInsta
used WKCookieWebView
as an embedded browser to handling cookies.
I looked at the original repo and it seems it is a known issue and I guess it fixed.
SwiftyInsta
doesn't use the latest update of the WKCookieWebView
and I think this is the problem.
As the Author said:
After running the app, before the first webview was loaded,
Cookies may not be set properly,
In that case, use the loader in advance to synchronize.WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)
I guess updating the WKCookieWebView
will help to fix it.
I'm a little busy for now to doing this update, I'll appreciate if you test it.
from swiftyinsta.
Edit: I'll try it with Siwa and i'll update this comment
Edit2: I can't even login with Siwa framework. It returns .inccorrectPassword, .invalidUsername
errors..
Okay, i was able to add second account. But when i am trying to switch between accounts i can't login the account that i am trying to switch in.
(i pass correct cookies inside isUserLoggedIn(instagramCookies : [HTTPCookie])
func )
try instagramHandler.login(cache: sessionCache) { (result) in
result.isSucceeded
coming as false when i am trying to switch to other account
public func isUserLoggedIn(instagramCookies : [HTTPCookie]) {
var isLogged = false
var csrfToken = ""
for i in 0..<instagramCookies.count {
let cookie = instagramCookies[i]
if cookie.name == "ds_user_id" {
isLogged = true
}
if cookie.name == "csrftoken" {
csrfToken = cookie.value
}
}
if isLogged {
let _urlSession = URLSession(configuration: .default)
let user = SessionStorage.create(username: "username", password: "password")
let instagramHandler = try! APIBuilder()
.createBuilder()
.setHttpHandler(urlSession: _urlSession)
.setRequestDelay(delay: .default)
.setUser(user: user)
.build()
let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (instagramCookies.toCookieData()), isUserAuthenticated: true)
// try? instagramHandler.login(cache: sessionCache, completion: { (result) in })
do {
try instagramHandler.login(cache: sessionCache) { (result) in
if result.isSucceeded {
print("\n\n LOGGED IN \n\n")
if self.loginDelegate != nil {
self.loginDelegate?.userLoggedSuccessfully()
}
InstaEndPoint.sharedInstance.handler = instagramHandler
self.getUser(instagramCookies: instagramCookies, handler: instagramHandler, csrfToken: csrfToken)
} else {
print("login failed")
}
}
} catch {
print("LOGIN ERROR")
}
} else {
}
}
from swiftyinsta.
Edit: I'll try it with Siwa and i'll update this comment
Edit2: I can't even login with Siwa framework. It returns.inccorrectPassword, .invalidUsername
errors..Okay, i was able to add second account. But when i am trying to switch between accounts i can't login the account that i am trying to switch in.
(i pass correct cookies insideisUserLoggedIn(instagramCookies : [HTTPCookie])
func )
try instagramHandler.login(cache: sessionCache) { (result) in
result.isSucceeded
coming as false when i am trying to switch to other accountpublic func isUserLoggedIn(instagramCookies : [HTTPCookie]) { var isLogged = false var csrfToken = "" for i in 0..<instagramCookies.count { let cookie = instagramCookies[i] if cookie.name == "ds_user_id" { isLogged = true } if cookie.name == "csrftoken" { csrfToken = cookie.value } } if isLogged { let _urlSession = URLSession(configuration: .default) let user = SessionStorage.create(username: "username", password: "password") let instagramHandler = try! APIBuilder() .createBuilder() .setHttpHandler(urlSession: _urlSession) .setRequestDelay(delay: .default) .setUser(user: user) .build() let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (instagramCookies.toCookieData()), isUserAuthenticated: true) // try? instagramHandler.login(cache: sessionCache, completion: { (result) in }) do { try instagramHandler.login(cache: sessionCache) { (result) in if result.isSucceeded { print("\n\n LOGGED IN \n\n") if self.loginDelegate != nil { self.loginDelegate?.userLoggedSuccessfully() } InstaEndPoint.sharedInstance.handler = instagramHandler self.getUser(instagramCookies: instagramCookies, handler: instagramHandler, csrfToken: csrfToken) } else { print("login failed") } } } catch { print("LOGIN ERROR") } } else { } }
Also having this problem
from swiftyinsta.
@mkeshnoda
@RealOlympusDev
When you pass the second cookie to instagramHandler.login(cache: sessionCache)
what is the error when it returns false?
My guess is you are receiving user must be authenticated.
error.
I faced this error when I was trying to implement this feature.
If you faced this issue, go to APIHandler.swift
file and comment the validateLoggedIn
function's body.
Note: make sure to clean build project to apply this change to framework.
If it solved your problem, let me know to release a fix for this function.
from swiftyinsta.
I don't remember the error to be honest, i already deleted Siwa framework. Because SwiftyInsta itself was enough, but my multiple account problem is still on the table. For now i just won't add multiple account feature.
But now, when i logout and login with other account framework still catches the first account's cookies :/ now i am trying to solve that problem
from swiftyinsta.
I believe I got that error but I also switched back to WebView, I tried the new version of WKWebViewCookie, but I still had to do it twice in order for it to change to the new data
from swiftyinsta.
@mkeshnoda this problem is not related to Siwa
, I believe this is the problem which prevents you to load your cookies.
@RealOlympusDev I know what you're saying, for sure this is WKWebViewCookie problem, because we delete every cookies before requesting new one.
Just try to comment the function I mentioned above, share the results here. I think it will fix your problem.
from swiftyinsta.
Yup, Now i don't have any problems with Siwa. which, i am not even use it at the moment. My problem is just; when i logout and login with other user i just can't get new user's cookies. I'll try to fix it again and i can i'll share the solution here.
from swiftyinsta.
@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?
from swiftyinsta.
@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?
go to APIHandler.swift
file and comment the validateLoggedIn
function's body.
from swiftyinsta.
@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?go to
APIHandler.swift
file and comment thevalidateLoggedIn
function's body.
Oh, ok
from swiftyinsta.
Fixed it! Had to add a completion handler to webViewFinishedToLoadUser and call self.deleteCookies() on completion of webViewFinishedToLoadUser.
from swiftyinsta.
(This requires the developer using the api to call your completion method at the end of their code)
from swiftyinsta.
Did you add multiple account feature or something else? @RealOlympusDev
from swiftyinsta.
@mkeshnoda I just have a thing that logs in and out, so when you log out and log back in to a different account it doesnβt load the same account anymore.
from swiftyinsta.
Can you share your codebase with me please (only necessary parts) π―ββ Because i did a lot of changes in my InstagramLoginWebView. If you want you can send it to [email protected] as well
from swiftyinsta.
@RealOlympusDev @mkeshnoda
Any fix?
from swiftyinsta.
From my side, no. unfortunately...
from swiftyinsta.
Same issue, when I want to login another account, the cookie is still the first one, even if I clean all cookies with the codes inside.
from swiftyinsta.
I still didn't have time to check it out. I'll probably try it again within a week. I'll keep here updated.
from swiftyinsta.
Hi, again @TheM4hd1
I tried @sbertix 's solution. I was able to login but i can't login automatically when i restart my app.
What i did there was;
1- Saved cookies with user defaults.
2- And i passed those cookies into isUSerLoggedIn(instagramCookies : [HTTPCookie]?)
Problem : handler is not working. It returns loginRequired error.
How can i fix this?
from swiftyinsta.
Prego π @mkeshnoda
from swiftyinsta.
Related Issues (20)
- LoginWebViewController can't login HOT 5
- Get isFollowedByYou Property while fetch users own followers HOT 1
- PaginationParameters.nextMaxId always nil when querying Inbox HOT 5
- Maintainers needed
- Test HOT 1
- Test HOT 2
- how to parse response? HOT 1
- how can get account activity list in swiftyinsta ? HOT 1
- Modifying thread_message_limit when requesting the Inbox HOT 1
- handler.requests is nil HOT 4
- Pagination HOT 2
- follower count HOT 1
- pagination HOT 1
- Enum cases with associated values cannot be marked potentially unavailable with '@available' HOT 3
- fetch followers issue HOT 1
- About Download Reels Using Copy Link HOT 1
- Authorization has stopped working! HOT 3
- login completion not working HOT 1
- New maintainers or fork? HOT 2
- LoginWebViewController can't login, no return sessionid HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swiftyinsta.