0

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.

3
  • you could look at these examples and explanations: docs.swift.org/swift-book/LanguageGuide/… There are examples of how to insert and remove strings and characters, plus a section on substring. Commented Sep 9, 2021 at 12:49
  • I have multiple parameters can I use a dictionary for this or u have any other idea? Commented Sep 9, 2021 at 13:01
  • Would it be possible in your use case to break the string up into components? Then you can run functions on video player size and the device id. It might look something like: let url = "urldomain.com/livestream_id(getPlayerSize()&(getDeviceID()))". Then each one of those functions can return the appropriate string if it exists. Commented Sep 9, 2021 at 13:18

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.