eric long eric long - 2 months ago 19
iOS Question

swift - substring from string

I have some of url string like:

let url1 = "https://abc/help?user_info_id=5#help-article03"

let url2 = "https://cde?user_info_id=455&artical=4"

let url3 = "https://ghi/help?user_info_id=5"

Now i want to get user_info_id from these urls.

url1 return 5, url2 return 455 and url3 return 5

This is my code

func getID(string: String) -> String {
let range = string.rangeOfString("user_info_id=")
guard let endIndex = range?.endIndex else { return "" }
let remain = string.substringFromIndex(endIndex)

let num = "0123456789"
var result = ""
for c in remain.characters {
if num.containsString(String(c)) {
result.append(c)
} else {
break
}
}
return result
}


Please tell me your idea. Thank you!

Answer

Use (NS)URLComponents and filter the query items:

let url1 = "https://cde?user_info_id=455&artical=4"
if let components = NSURLComponents(string: url1),
  let queryItems = components.queryItems,
  let userInfoId = queryItems.filter({$0.name == "user_info_id"}).first where userInfoId.value != nil {
  print(userInfoId.value!)
}
Comments