简体   繁体   中英

Translate rangeOfString from Objective-c To Swift

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM