Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect to TwilioChatClient when internet is off #13

Open
Hamza123Imran opened this issue Feb 12, 2019 · 0 comments
Open

Connect to TwilioChatClient when internet is off #13

Hamza123Imran opened this issue Feb 12, 2019 · 0 comments

Comments

@Hamza123Imran
Copy link

Hi, i have a chat app i'm using twilio in that. Now my backend developer has configure the backend properly. When i run app i hit an API to my backend server and in response i get the twilio chat token. Then i initialize the chat client. This works fine, now when i want to run my app when app is not connected to internet. For this i store the twilio chat token in my core data entity and sent this stored token for my function that initialize the TwilioChatClient. Now when i hit these commands when internet is not connected, it shows me Client is not connected in my console. Now i have a question that how can i connect myself to TwilioChatClient when my internet is off. This is the code that how i get the twilio token from my backend server through API,
`func fetchTwilioToken(_ myNumber: String, completion: @escaping ((Bool) -> Void)) {

    //Check internet status
    netStatus = UserDefaults.standard.string(forKey: "netStatus")!
    print(netStatus!)

    network.reachability.whenReachable = { reachability in
        self.netStatus = "Yes"
    }

    network.reachability.whenUnreachable = { reachability in
        self.netStatus = "No"
    }
    
    if netStatus == "Yes"
    {

    let deviceId = UIDevice.current.identifierForVendor!.uuidString
    let params : [String : Any] = ["token" : myNumber, "deviceId": deviceId]
    print(params)
    ServerCall.makeCallWitoutFile(TwilioChatTokenUrl, params: params, type: Method.POST, currentView: nil) { (response) in
        
        if let json = response {
            print(json)
            setTwilioChatToken(token: json["twillio_token"].stringValue)
            let token = json["twillio_token"].stringValue
            print(token)
            
            let appDelegate = UIApplication.shared.delegate as? AppDelegate
            let context = appDelegate?.persistentContainer.viewContext
            let entity = NSEntityDescription.entity(forEntityName: "TwilioChatTokenCoreData", in: context!)
            let user = NSManagedObject(entity: entity!, insertInto: context)

            user.setValue(token, forKey: "twilioToken")
            do {
                try context?.save()
                print("Saved successfully.")
                self.getTwilioTokenData({(client) in
                    if client
                    {
                        completion(true)
                    }
                    else
                    {
                        completion(false)
                    }

                })

            } catch  {
                print("Fail to save")
            }
            self.initiateChatClient({ (clientRcvd) in
                if clientRcvd {
                    completion(true)
                }else {
                    completion(false)
                }
            })
        }else {
            completion(false)
            topViewController()?.showAlert("Connection is Weak!\nChat is not updated")
       
        }
        }
    }
    else
    {
        self.getTwilioTokenData({(client) in
            if client
            {
                completion(true)
            }
            else
            {
                completion(false)
            }
            
        })
    }
}`

And this is how i pass my stored twilio chat token to initialize chat client,
` func initiateChatClient(_ completion: @escaping ((Bool) -> Void)) {

  //  if let token = TwilioChatToken {
    let token  = twilioToken
    print(token)
    TwilioChatClient.chatClient(withToken: token, properties: nil, delegate: self) {
            (result, chatClient) in
            
            if let client = chatClient {
                print("Reachability: \(client.isReachabilityEnabled())")
                self.chatClient = client
                appDeleg.chatClient = client
                if let username = client.user?.friendlyName {
                    print("Logged in as \(username)")
                }else {
                    if let user = UserDefaults.standard.object(forKey: key_My_Profile) as? UserProfile {
                        client.user?.setFriendlyName(user.name, completion: { (results) in
                            print(result.resultText!)
                        })
                    }
                }

                completion(true)
            }else {
                completion(false)
                print("Client is not connected")
                topViewController()?.showAlert("Connection is Weak!\nChat is not updated")
            }
        }
    //}
}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant