Getting a value from url by using components separated by string - ios

I have a url that looks like this :
https://google.com/image/ghwUT23Y.jpeg
I want to be able to achieve something like this:
section = image;
value = ghwUT23Y;
I have tried to explode the url and usecomponentsSeperatedByStringmethod to grab the values I need.
if ([[explodedUrl firstObject] containsString:#"google.com"] && ![[explodedUrl firstObject] isEqualToString:#"https://google.com/"]) {
NSString *sectionString = [[[explodedUrl lastObject] componentsSeparatedByString:#"/"] firstObject];
NSLog(#"redirectttttt: %#",sectionString);
NSString *itemString = [[[explodedUrl lastObject] componentsSeparatedByString:#"/"] lastObject];
NSLog(#"redirectttttt:2 %#",itemString);
Problem:
Using this method, itemString returns me the value : ghwUT23Y.jpegbut sectionString returns me https://
How would I be able to get image as a section?

You need to convert your string to url first and use the pathComponents method to access each components of that url.
Objective C:
NSURL *url = [NSURL URLWithString:#"ttps://google.com/image/ghwUT23Y.jpeg"];
NSMutableArray *components = [[url pathComponents] mutableCopy];
NSString *fileName = [components lastObject];
[components removeLastObject];
NSString *section = [components lastObject];
NSLog(#"File : %#, Section: %#",fileName, section);
Swift
let url = URL(string: "https://google.com/image/ghwUT23Y.jpeg")
var components = url?.pathComponents
let fileName = components?.popLast()
let section = components?.popLast()

Swift :
func detectUrl() {
let strLongDescription = "https://google.com/image/ghwUT23Y.jpeg"
if(strLongDescription.contains("image")){
var arrString : [String] = strLongDescription.components(separatedBy: "google.com/")
let lastOfarrString : String = arrString.last!
arrString = lastOfarrString.components(separatedBy: "/")
let section = arrString.first!
let value = arrString.last!
}
}

Related

How to get highlighted text range in WebView Content in iOS?

Applied this code in .js file
var selectedText = "";
function getHighlightedString()
{
var text = document.getSelection();
startIndex = text.anchorOffset;
endIndex = text.focusOffset;
selectedText = text.anchorNode.textContent.substr(startIndex,endIndex - text.anchorOffset);
var rangeText = document.getSelection().toString();
}
function highlight() {
if (typeof window.getSelection != "undefined") {
var range = document.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "rgb(237,191,245)";
span.style.color = "orange";
range.insertNode(span);
}
}
And I'm using this code for highlighting the text.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"first" ofType:#"js" inDirectory:#""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[webView_Detail stringByEvaluatingJavaScriptFromString:jsString];
NSString *highlightFunction = [NSString stringWithFormat:#"highlight()"];
[webView_Detail stringByEvaluatingJavaScriptFromString:highlightFunction];
highlightedString = [webView_Detail stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
I stuck for getting the text range. it i have to send to server.but i couldn't able to get selected text range.
Please help me.
Try Following
NSString * strJS = #"window.getSelection().toString()";
NSString * strSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:strJS];
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString:#"document.body.textContent"];
NSRange * rangeOfString = [plainText rangeOfString:strSelectedText];
You can try following alternate also
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.innerText"];
If there are multiple matches found for selected text, please refer following link to find all ranges of occurrence.
Find all locations of substring in NSString (not just first)

Format a NSMutableArray object to a string

array is a NSMutableArray. I am adding some string objects to it.
[array addObject:#"MM-19"];
[array addObject:#"MM-49"];
[array addObject:#"MM-165"];
[array addObject:#"MM-163"];
Now, I need to write a method that will return me a NSString in the following format :
19-49-165-163
How can this be done ?
Here is your solution,
NSString *dashSeperatedString = [array componentsJoinedByString:#"-"] ;
dashSeperatedString = [dashSeperatedString stringByReplacingOccurrencesOfString:#"MM-" withString:#""] ;
NSLog(#"Output : %#", dashSeperatedString);
Try this code will help,
NSString *finalString = #"" ;
for (NSString *strvalue in array)
{
NSArray *temp= [strvalue componentsSeparatedByString:#"-"];
if ([strvalue isEqualToString:array.lastObject])
{
finalString= [finalString stringByAppendingString:temp.lastObject];
}
else
{
finalString= [finalString stringByAppendingString:[NSString stringWithFormat:#"%#-",temp.lastObject]];
}
}
NSLog(#"%#",finalString);
Another alternative could be:
NSString *combinedStuff = [array componentsJoinedByString:#""];
combinedStuff = [combinedStuff stringByReplacingOccurrencesOfString:#"MM" withString:#""];
if ([combinedStuff hasPrefix:#"-"])
{
combinedStuff = [combinedStuff substringFromIndex:1];
}
Swift 2.0:
let mutableArray = NSMutableArray()
mutableArray.addObject("MM-19")
mutableArray.addObject("MM-49")
mutableArray.addObject("MM-165")
mutableArray.addObject("MM-163")
var finalString = String()
finalString = ""
for stringValue in mutableArray {
let temp: [AnyObject] = stringValue.componentsSeparatedByString("-")
finalString = finalString.stringByAppendingString(String(temp.last)+"-")
}
print("Final String: \(finalString)")
OR
var finalSeperatedString: String = mutableArray.componentsJoinedByString("-")
finalSeperatedString = finalSeperatedString.stringByReplacingOccurrencesOfString("MM-", withString: "")
print("Output String: \(finalSeperatedString)")
}

How to separate NSString with multiple commas?

Am having this nsstring
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
now i want to display only the countries which are suffixed by "en_US".
can anybody tell me how to split that string to get the countries.
I did like this
NSError * error;
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"CountryList" ofType:#"txt"];
NSString * countrStr = [NSString stringWithContentsOfFile:imageName encoding:NSStringEncodingConversionAllowLossy error:&error];
NSArray * dfd = [countrStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<dfd.count;i++)
{
NSString * nama = [dfd objectAtIndex:1];
NSArray * djk = [nama componentsSeparatedByString:#","];
NSString * aksjd = [djk objectAtIndex:1];
}
You can do it like this;
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
NSArray * arrData = [countryStr componentsSeparatedByString:#","];;//[countryStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<arrData.count;i++)
{
NSString * str = [arrData objectAtIndex:i];
if ([str isEqualToString:#"en_US"] && i<arrData.count-1)
{
NSString* countryName = [arrData objectAtIndex:i+1];
NSLog(#"countryName %#", countryName);
}
}
But you should manage data in your file, loading from resource.
Best way to do it is
NSString *string = [NSString stringWithFormat: #"%#, %#, %#", var1, var2, var3];
Excuse the formatting/syntax errors. Typing this via iPhone. But if there is any errors, look up stringWithFormat: in iOS documents on the apple developer page for corrections.
Your string seems to have the following pattern:
A number,
An other number,
The country language code,
The name,
A short code,
An (other) name.
So what you can do is to use a loop like this:
for (int i = 0; i < dfd.count; i += 6) {
if ( dfd[i + 2] ) } // check the country code at index i + 2
// Do something
}
}

Extract required string from a string

Hey i am new to ios I want to get part of string from a string,
the original string is,
OriginalString=#"access_token=CAAEW97M253kB2BZBg9VysMCkOyjDi6HtvLcqtkh3Xp5y4ZBZCExq8ZCCZCKo2QZAJ8lSQ9EvOhtPPxr0pLM5NgNE5jFC1blzn8tu0xhvOcXIn&expires=5178989";
i want to get "&expires=5178989" this.
If it will always be this format, you can can do:
NSArray *components = [originalString componentsSeparatedByString:#"&"];
Your string will be the second object. Retrieve it with:
NSSTring *expires = [components lastObject]
- (NSString *)extractString:(NSString *)fullString toLookFor:(NSString *)lookFor skipForwardX:(NSInteger)skipForward toStopBefore:(NSString *)stopBefore
{
NSRange firstRange = [fullString rangeOfString:lookFor];
NSRange secondRange = [[fullString substringFromIndex:firstRange.location + skipForward] rangeOfString:stopBefore];
NSRange finalRange = NSMakeRange(firstRange.location + skipForward, secondRange.location + [stopBefore length]);
return [fullString substringWithRange:finalRange];
}
call this function like this
NSString *strTemp = [self extractString:#"abcdefwww.google.comabcdef" toLookFor:#"www" skipForwardX:0 toStopBefore:#".com"];
NSLog(#"\n\n Substring ==>> %#",strTemp);

Extracting values from the url in iOS

my url is https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807
i want to extract the value of user & albumid, i had tried to extract with different methods which i found in stack overflow ,but they didn't work.
Please help me out.
Thank you for your precious time.
You can take your NSURL (or init one from the URL string), and use the method pathComponents which return an array of the words in the URL (separated from the slash /), so:
pathComponents[0] == #"photos.googleapis.com"
pathComponents[1] == #"data"
...etc.
Here the snippet of code:
NSURL *url = [NSURL urlWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSString *user = url.pathComponents[9];
NSString *album = url.pathComponents[11];
I give you an example here, NSURL class is your friend. You can use e.g. pathComponents: to get an array of all components and then process this array as you need it:
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *components = [url pathComponents];
NSLog(#"path components: %#", components);
NSLog(#"user: %#", components[9]);
NSLog(#"albumid: %#", components[11]);
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *pathComponentsArray = [url pathComponents];
NSString*userValue;
NSString*albumidValue;
for(int i=0;i<[pathComponentsArray count];i++)
{
if([pathComponentsArray[i] isEqualToString:#"user"])
{
userValue = pathComponentsArray[i+1];
}
if([pathComponentsArray[i] isEqualToString:#"albumid"])
{
albumidValue = pathComponentsArray[i+1];
}
}

Resources