Translate rangeOfString from Objective-c To Swift

850 views Asked by At

I'm trying for hours to translate this short code. Objective C :

NSString *urlStr = [request.URL absoluteString];
NSArray *urlParts = [urlStr componentsSeparatedByString:[NSString stringWithFormat:@"%@/", kREDIRECTURI]];

if (urlParts.count > 1)
{
    urlStr = urlParts[1];
    NSRange token = [urlStr rangeOfString:@"#access_token="];

    if (token.location != NSNotFound)
    {
        vc.access_token = [urlStr substringFromIndex:NSMaxRange(token)];
    }
}

What i have tried :

Swift :

var urlParts : NSArray = urlStr!.componentsSeparatedByString("\(kREDIRECTURI)")
if urlParts.count > 1
{
    urlStr = urlParts[1] as? String
    var token  = urlStr!.rangeOfString("#access_token=", options: NSStringCompareOptions.allZeros) as NSRange!

    if token != nil
    {
         var vc = ViewController()
         urlStr!.substringFromIndex(NSMaxRange(token))!
    }
}

Any idea?

1

There are 1 answers

6
Sandeep On BEST ANSWER

I will assume that the access_token query parameter is at the end and the code follows the string like this 'http:\...#access_token=', the url ends with the code at the end. Here is a simple method that would extract the code out of the url,

func getTokenFromUrl(url: String) -> String? {

    let range1 = url.rangeOfString("#access_token")

    guard let range = range1 else { return nil }

    let startIndex = range.endIndex.successor()
    let rangeOfToken = url.endIndex

    let rangeOfString = startIndex ..< rangeOfToken

   return  url.substringWithRange(rangeOfString)
}

let url1 = "http://stackoverflow.com/questions/31010975/translate-rangeofstring-from-objective-c-to-swift?#access_token=873jasf82jmsa8sd"

let url2 = "http://stackoverflow.com/questions/31010975/translate-rangeofstring-from-objective-c-to-swift"

getTokenFromUrl(url1) // returns 873jasf82jmsa8sd
getTokenFromUrl(url2) // returns nil

For earlier version of Swift, you could use if let patter to unwrap the optional,

func getTokenFromUrl(url: String) -> String? {

    let range1 = url.rangeOfString("#access_token")

    if let range = range1 {

        let startIndex = range.endIndex.successor()
        let rangeOfToken = url.endIndex

        let rangeOfString = startIndex ..< rangeOfToken

       return  url.substringWithRange(rangeOfString)
    }
    return nil
}