kuldeep bhandari
kuldeep bhandari

Reputation: 1

Remove the existing string and append a new string for that string

I have a video URL like this

urldomain.com/livestream_id/PLAYER_WIDTH&PLAYER_HEIGHT&IDFA_ID&DEVICE_ID

If the video URL contains the PLAYER_WIDTH&PLAYER_HEIGHT so I have to replace this string with this &sd=1960*1080, and if it does not contain IDFA_ID so I have to remove this from the URL, and if this contains DEVICE_ID so I have to replace DEVICE_ID with this device_id="myDeviceid".

so my final URL looks like this

urldomain.com/livestream_id/?sd=1960*1080&deviceId="myDeviceid"

can anyone tell me how can I do this.

Upvotes: 0

Views: 295

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

No need to replace substrings in your string. You should use URLComponents to compose your URL. This way you don't have also to manually percent encode your string.

var components = URLComponents()
let scheme = "https"
let host = "urldomain.com"
let path = "/livestream_id/"
let sd = "1960*1080"
let deviceId = "myDeviceid"
let sdItem =  URLQueryItem(name: "sd", value: sd)
let deviceIdItem =  URLQueryItem(name: "device_id", value: deviceId)
components.scheme = scheme
components.host = host
components.path = path
components.queryItems = [sdItem, deviceIdItem]
if let url = components.url {
    print(url.absoluteString)  // https://urldomain.com/livestream_id/?sd=1960*1080&device_id=myDeviceid
}

To customize the final url you can check if your string contains a keyword and if true just append the query item to the components queryItem property. Something like:

let urlString = "urldomain.com/livestream_id/PLAYER_WIDTH&PLAYER_HEIGHT&IDFA_ID&DEVICE_ID"
components.queryItems = []
if urlString.contains("PLAYER_WIDTH&PLAYER_HEIGHT") {
    components.queryItems?.append(sdItem)
}
if urlString.contains("DEVICE_ID") {
    components.queryItems?.append(deviceIdItem)
}

Upvotes: 2

Related Questions