0

I'm working with Swift 3 and Xcode 8 (iOS 10.1), I'm completely new to the whole world. :)

I'm authenticating against an external app to get an access token. The use case is:

1) Load external app from my app

2) Validate the user and get the access token

3) Redirect back to my app from external app

I am able to do 1) and 2), but not 3). The external app has specified that you configure a redirect parameter, and I've done that. But alas, no cigar.

I have set up URL schemes in Info.plist for both apps. I don't get any errors in the console or debugger.

I have been googling and researching for the past 4 days and this is the solution I have come up with so far. Right now, I see the console messages, but the external app is no longer opening up.

AppDelegate

  func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if (url.scheme == "extapp") {
        print("working with extapp scheme")
    } else if (url.scheme == "myapp") {
        print("redirecting back to app after working with extapp")
    }
    return true
  }

ViewController

@IBAction func loginButton(_ sender: Any) {
    let id = text.text
    let currentCharacterCount = id.text?.characters.count ?? 0
    if currentCharacterCount == 0 {
        self.showAlert(text: "Please provide a id.")
    } else if currentCharacterCount < 10 {
        self.showAlert(text: "Oh! id doesn't seem to be in the correct format. Try again.")
    } else {
        if (self.firebaseData.callAuth(loggedIn: id!)) {
            OpenExtApp()
        }
    }
}

func OpenExtApp() {
    let Url = URL(string: "extapp:///?autostart=\(token)&redirect=myapp://key")
    if (UIApplication.shared.canOpenURL(Url!)) {
        UIApplication.shared.open(Url!, options: [:])
    }
}

I would really appreciate your help in any way.

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
Mina
  • 610
  • 7
  • 21

2 Answers2

1

The problem appears to have been with the addingPercentEncodingmethod I was using to encode the redirect parameter. I didn't notice that the parameter wasn't being encoded properly. It turns out that the default filter in with AllowedCharacters doesn't encode / and :. It's a known issue with Apple. This solved the encoding problem and, in turn, the problem I was having with opening the extapp:

let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
let redirect = parameter.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed)
Mina
  • 610
  • 7
  • 21
0

Check this out and also make sure to add the custom schemes to your info.plist file How to handle custom url schemes in swift (XCode 8)?

Community
  • 1
  • 1
Ahmed
  • 938
  • 7
  • 16
  • thanks for your answer, Ahmed. My method signature in AppDelegate is as what is specified in the link you provided. – Mina Nov 18 '16 at 08:59