Taha Amini Taha Amini - 7 months ago 78
Objective-C Question

Getting a value from url by using components separated by string

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 use
componentsSeperatedByString
method 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.jpeg
but
sectionString
returns me
https://


How would I be able to get
image
as a section?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download