Syntax to put a variable in a string in swift3 - ios

A question I think pretty simple but I never had to do it in swift. it's pretty simple PHP but here I do not find my solution on the internet.
ask: I would like to add a variable in this chain of character. Instead of 123, I would need a variable.
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_123.json"
result = final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_VARAIBLE.json"
Can you give me the syntax in swift3 or direct me to a good tutorial.

You can create a string using string formatting.
String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)

let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
\(variable) is what you need
OR
use string formatting
let variable = 123
final let urlString = String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)

There is good documentation about Strings in Swift Language Guide. Your options are:
Concatenating Strings
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + value + ".json"
String interpolation
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(value).json"

Swift4 You can add a string in these ways:
var myString = "123" // Or VARAIBLE Here any string you pass!!
var urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(myString).json"

A simple way of doing it could be:
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variablename + ".json"
You can also do it like this (a little more typesafe):
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variablename).json"
Swift will read \(variablename) into the string automatically and accepts - among all things - integers.

let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variable + ".json"
or
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"

Related

How to separate two URLs in a String in Swift?

What is the best way to split this String into two using Swift?
"https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
I only need the second part of url in the String. In this example, in this case I just need:
"http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
let str = "https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
if let lastStr = str.components(separatedBy: "http").last
{
let result = "http" + lastStr
print(result)
}
Console Output: http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif

How to append an array in URL request type GET in Swift?

I am using Xcode7.3 with Swift2.2.
I want to append an Array in url request.For example my array like
[“jeevan”,”jeejo”]. I want to append this array with key(arrayKey) in url request like must be the following pattern
https://api.com/pre/ws/ch/roo?arrayKey=jeevan%2Cjeejo
How to solve this issue? Please help me
You need to use encode your URL instead of join Array with separator, but if you want to merge Array with URL you can try like this.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator("%2C")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
If you want to encode url encode this way.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator(",")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
let encoded = url.stringByAddingPercentEncodingWithAllowedCharacters(.URLFragmentAllowedCharacterSet())
Note : The reason I have used , is because %2C is encode for , you can confirm it here on W3School URL Encoding.
easy solution can be like this
var URIString = ""
for item in array {
URIString +=\(item)%2C
}
after subtract last 3 characters and make URL string
Simple code like this
var array: [String] = ["jeevan","jeejo"]
var myString = ""
for i in 0..<array.count {
myString += array[i]
if (i+1)<array.count { mystring+="%2C" }
}
Can give you result like this:
jeevan%2Cjeejo

Put a string before a certain string inside a text in Swift 3

I'm dealing with an issue here, I have a URL of an image which is like this
http://example.com/image/test.jpg
Which is a string.
And I would like to insert before .jpg a certain text like -40x40
Is there any way to analyze the URL string and somehow to add this text so the final string should be
http://example.com/image/text-40x40.jpg
What i've tried till now is this
var finalImage = "http://example.com/image/test.jpg"
finalImage.insert("-40x40" as Character, at: finalImage.endIndex - 4)
but i get 2 errors.
1) i cant add more than 1 character and 2) i cant do the math ad endIndex.
But i can't add more than one character there.
Thanks a lot!
Try this. It uses NSURL, which exists so that path manipulations are easy and legal! The documentation is really quite good.
let s1 = "http://example.com/image/test.jpg"
let u = URL(fileURLWithPath: s1)
let exExt = u.deletingPathExtension()
let s2 = exExt.absoluteString + "-40x40.jpg"
Another ways.
The code shown in the question, fixed:
var finalImage = "http://example.com/image/test.jpg"
let extIndex = finalImage.index(finalImage.endIndex, offsetBy: -4)
finalImage.insert(contentsOf: "-40x40".characters, at: extIndex)
Using NSRegularExpression:
let origImage = "http://example.com/image/test.jpg"
let regex = try! NSRegularExpression(pattern: "(\\.jpg)$", options: .caseInsensitive)
let finalImage = regex.stringByReplacingMatches(in: origImage, range: NSRange(0..<origImage.utf16.count), withTemplate: "-40x40$0")
As a complement to the neat accepted answer by #Grimxn: Foundation's URL has various more methods that allows for more separation "of concerns" in case you'd like to apply some more complex modification of the image (file) name, while not really worrying about the image (file) name extension.
let s1 = "http://example.com/something.cgi/image/test.jpg"
let u = URL(fileURLWithPath: s1)
// separate into (String) components of interest
let prefixUrl = u.deletingLastPathComponent().absoluteString
// "http://example.com/something.cgi/image/"
let fileName = u.deletingPathExtension().lastPathComponent
// "test"
let fileExtension = "." + u.pathExtension
// ".jpg"
// ... some methods that implements your possibly more
// complex filename modification
func modify(fileName fName: String) -> String {
// ...
return fName + "-40x40"
}
// reconstruct url with modified filename
let s2 = prefixUrl + modify(fileName: fileName) + fileExtension
print(s2) // http:/example.com/something.cgi/image/test-40x40.jpg
Grimxn's solution is probably the best fit for this problem, but for more complex manipulation of URLs, take a look at the NSURLComponents class. You can convert an NSURL to NSURLComponents, then use the various methods of NSURLComponents to manipulate your URL, and then finally convert the NSURLComponents back to an NSURL
As noted in a comment by #dfri, Swift 3 (and later) includes a native URLComponents class, which follows Swift naming and calling conventions. Going forward you should use that instead of the Objective-C/Swift 2 NSURLComponents class.
if let url = NSURL(string: "http://example.com/image/test.jpg"),withoutExt = url.URLByDeletingPathExtension
{
let finalstring : NSString = withoutExt.absoluteString + "-40x40.jpg"
print(finalstring)
}
Very simply with one line...
let newURL = oldURL.stringByReplacingOccurrencesOfString(".jpg", withString: "-40x40.jpg", options: NSStringCompareOptions.LiteralSearch, range: nil)

How to extract phrase from string using Range? [duplicate]

This question already has answers here:
Finding index of character in Swift String
(33 answers)
Closed 6 years ago.
This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.
I have a URL like this:
https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post
I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.
urlString.rangeOfString("#") returns Range
Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))
Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:
import Foundation
let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
fragment = url.fragment {
print(fragment)
}
// output: "global-best-time-to-post"
// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
let fragment = split.last {
print(String(fragment))
}
// output: "global-best-time-to-post"
// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
// Note that I use the index of the end of the found Range
// and the index of the end of the urlString to form the
// Range of my string
let fragment = urlString[endOctothorpe..<urlString.endIndex]
print(fragment)
}
// output: "global-best-time-to-post"
You could also use substringFromIndex
let string = "https://github.com..."
if let range = string.rangeOfString("#") {
let substring = string.substringFromIndex(range.endIndex)
}
but I'd prefer the NSURL way.
use componentsSeparatedByString method
let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")
your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase
var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)

How to get URL and its parameter value in F#

Is there any way to get URL and further its parameter values in f# Only F# any one can help me. I have tried a lot but no solution found
http://www.example.com/blog?blogid=23
Want to get http://www.example.com/blog?blogid=23
Then 23
let getBlogId uriString =
let uri = System.Uri(uriString)
let kvps = HttpUtility.ParseQueryString uri.Query
let idStr = kvps.["blogid"]
int idStr
let uri = new System.Uri("http://www.example.com/blog?blogid=23")
let blogId = uri.Query.Split('=').[1]

Resources