How do I get a string between slashes -Swift - ios

I have string like so "/blah//hahaha//lalala/"
Which needs to be translated into an Array of strings so that if I printed the array it would look like this print(arrayOfStrings) // prints ["blah","hahaha","lalala"]
I am new to swift so forgive me if this question is foolish

Given
let text = "/blah//hahaha//lalala/"
you can
let chunks = String(text.characters.dropFirst().dropLast()).componentsSeparatedByString("//")
and this is what you get
["blah", "hahaha", "lalala"]

There's also the URL solution
let string = "/blah//hahaha//lalala/"
let components = NSURL(fileURLWithPath: string).pathComponents!.dropFirst()
print(components)

Related

Converting string (Contains json string) to NSURL in swift

I have PAI its Implemented in .NET.
one of the web service url is like this
http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}
while converting above string to URL in swift, app going crash.
for more info check this
The URL(string:) initializer returns an optional since the parsing of the string may fail. In that case, nil is returned. That's exactly what's happening here since the string you are providing is not a valid URL: there are several characters in the query that are not allowed there and need to be replaced: { as %7B, " as %22, space as %20 and } as %7D.
So the initializer returns nil. Next thing you do is force unwrap via the ! operator. But force-unwrapping a nil is illegal and is why you get the crash.
If you want to create an URL, please look into the URLComponents class which does all the necessary escaping for you so you don't need to care about it. The queryItems property is of particular interest for you, it's an array of URLQueryItem.
Please do something like that,
let jsonString = "jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}" as String
let urlEncoadedJson = jsonString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
let urls = NSURL(string:"http://123.321.33/UploadCitizenImage?\(urlEncoadedJson ?? "")")
First convert your json into encodedJson then add into your url.
Do let me know if there is some issue.
You can try this,
let string = "http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}"
let escapedString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: escapedString!)!
print(url)
Output will be like this,
http://123.321.33/UploadCitizenImage?jsonString=%7B%22Mobile%22:%2212345678%22,%20%22fileName%22:%227661832460_05072018.png%22%7D

Converting a multi dimensional string array into doubles

I have been trying to parse a CSV file forever and I am almost there. I have gotten it to a multi-dimensional array of strings using this code:
let path = Bundle.main.url(forResource: "BaseballSimStats", withExtension: "csv")
var file = String()
do {
file = try String(contentsOf: path!)
print(file)
} catch {
print(error)
}
let stringarray = file.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") }
Now the last step is to turn it into a Double. I am using this code:
probs = Double[[stringarray]]
I get an error saying that the type has no subscript errors. I get rid of the subscript references and the error goes away. Why is this error here and how can I get rid of it? Thanks!
I used .map() to map the String into a Double, this should work for nested array
var strArray = [["1.00000","1.10000"],["2.00000","2.10000"]]
var doubleArray = strArray.map { (arr: Array) -> Array<Any> in
return arr.map({ (value: String) -> Double in
return Double(value)!
})
}
print(strArray)
print(doubleArray)
I am not sure if the double map was needed.
I am not a swift guru but this code should help you achieve what you want..
I'm not familiar with Double[[stringarray]] syntax so I don't know how that's supposed to work. I do know you can't just cast between array types.
The simplest way is probably to wrap the innermost call with Double.init():
file.components(separatedBy: "\n").map{ $0.components(separatedBy: ",").map { Double($0)! }}
Of course, there's a bit more to CSV than just splitting on commas and assuming everything is a valid number, so I'd highly recommend using an existing CSV parsing library for any real data.

Wrong language code swift

I set the language of the simulator to French. To check the language code, I used a couple of solutions:
let lang = NSLocale.autoupdatingCurrent.languageCode
print(lang)
let pre = Locale.preferredLanguages[0]
print(pre)
The result are:
Optional("en")
fr-US
What I expected to get is:
fr
How can I achieve that?
Try below code,
let requiredString = pre.components(separatedBy: "-").first ?? pre //fr
/*if pre.contains("-"), then requiredString = before("-") else requiredString = pre*/
print(Locale.components(fromIdentifier: Locale.preferredLanguages[0])["kCFLocaleLanguageCodeKey"]!)
this will print language code only.
If you want the Language instead of the Language_Region, then I suggest to take the sub string before the _ from the string to neglect the Region.
(If the string contains no _ then take the entire string since it doesn't contain the region in it)

String encoding - Swift

I am using the following method to encode a string in objective - C:
+(NSString*)urlEncoded:(NSString*)string
{ return ((NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (NULL,(CFStringRef)string, NULL,(CFStringRef)#"! '=();#&+$%#",kCFStringEncodingUTF8 )));}
Is there any counterpart for this method in Swift 2.0 ? I have tried using many solutions present on stack, but none of them could solve my problem.
You probably want to use stringByAddingPercentEncodingWithAllowedCharacters with NSCharacterSet's URL-component specific character sets:
let title = "NSURL / NSURLComponents"
let escapedTitle = title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
The idea behind those character sets is that they're probably more correct for the uses they describe than any finite set you have. That said, you could use the same method with a set you generate yourself:
let escapeSet = NSCharacterSet(charactersInString: "! '=();#&+$%#")
let string = "sdfT&*w5e#sto([+peW7)%y9pqf])"
let escapedString = string.stringByAddingPercentEncodingWithAllowedCharacters(escapeSet.invertedSet)
// "sdfT%26*w5e%23sto%28[%2BpeW7%29%25y9pqf]%29"

insert a String inside another String

How can I make this:
var originalString = "http://name.domain.com/image.jpg"
becomes this:
originalString = "http://name.domain.com/image_new.jpg"
I could not find any document about the new Range<String.Index> in Swift.
This is not a problem in Obj-C, but without any reference about Range, it suddenly becomes so confusing.
Thanks.
Edit:
Well, thanks for these solutions. However, let me give you more details about this question.
After uploading an image to server, it responds back with a String link, like above, and the image name is a random string.
The server also generates different versions of uploaded image (like Flickr). In order to get these images, I have to append a suffix into image name, it looks like this:
originalString = "http://image.domain.com/randomName_large.jpg" or "http://image.domain.com/randomName_medium.jpg"
So that's why I need to insert a String into another String. My solution is find the first . by scan the link backwardly and append a suffix before it, but the new Range<String.Index> makes it confusing.
There are some nice and useful methods on NSString that you should be able to use:
let originalString: NSString = "http://name.domain.com/image.jpg"
let extension = originalString.pathExtension // "jpg"
let withoutExt = originalString.stringByDeletingPathExtension() // "http://name.domain.com/image"
let imageName = withoutExt.lastPathComponent // "image"
let withoutFilename = withoutExt.stringByDeletingLastPathComponent() // "http://name.domain.com/"
let newString = withoutFilename
.stringByAppendingPathComponent("\(imageName)_new")
.stringByAppendingPathExtension(extension)
I only typed this into the browser (it's untested) but it should give you an idea...
This can be done with String manipulation functions. But what if the string
is
var originalString = "http://images.domain.com/image.jpg"
? You probably do not want to replace the first or all occurrences of the string
"image" here.
A better tool for this purpose might be NSURLComponents, which lets you
modify all components of a URL separately:
var originalString = "http://name.domain.com/image.jpg"
let urlComps = NSURLComponents(string: originalString)!
urlComps.path = "/image_new.jpg"
originalString = urlComps.URL!.absoluteString!
println(originalString) // http://name.domain.com/image_new.jpg
Why not using string interpolation?
var imageName = "image_new"
originalString = "http://images.domain.com/\(imageName).jpg"

Resources