Reputation: 5920
I have this if
statement to check if a URL starts with a prefix:
NSString *baseUrl = @"http://example.com/";
NSString *currentURL = @"http://example.com/confirm";
if( [currentURL hasPrefix:[baseUrl stringByAppendingString:@"confirm"]] ){
// True, so do something...
}
I would like to modify the hasPrefix
part of my if
statement so that it returns true if currentUrl
is appended by ANY of the values in my NSArray
shown here:
NSArray *pages = [NSArray arrayWithObjects:@"confirm",@"products",nil];
How can I do this?
Upvotes: 2
Views: 4633
Reputation: 11462
It's simple, use following code
BOOL hasPrefixInArray = NO;
for(int i = 0; i < [array count] && hasPrefixInArray == NO; i++)
{
hasPrefixInArray = [yourString hasPrefix:array[i]];
}
// check value here for hasPrefixInArray
NSLog(@"%d",hasPrefixInArray);
Upvotes: 0
Reputation: 2990
For the ones who want to avoid Carpal Tunnel Syndrome:
NSString *baseUrl = @"http://example.com/";
NSString *currentURL = @"http://example.com/confirm";
NSArray *pages = [NSArray arrayWithObjects:@"confirm",@"products",nil];
BOOL hasSuffix = NO;
[pages enumerateObjectsUsingBlock:^(NSString* page, NSUInteger idx, BOOL *stop) {
if([currentURL hasPrefix: baseUrl] && [currentURL hasSuffix: page]){
hasSuffix = YES;
stop = YES;
}
}];
Your description sounds more like you are looking for a suffix, so there you have it.
Upvotes: 0
Reputation: 222
just iterate through your pages array and set a boolean flag if any of the terms exist
//
// customstring.m
//
// Created by rbertsch8 on 8/2/13.
//
//
#import "customstring.h"
@implementation customstring
-(bool)hasPrefixArray:(NSArray*)array withbaseURL:(NSString*)baseUrl
{
bool hasprefix = NO;
for(int i = 0; i < [array count] || hasprefix == NO; i++)
{
hasprefix = [self hasPrefix:[baseUrl stringByAppendingString:[array objectAtIndex:i]]];
}
return hasprefix;
}
@end
Now in your code do the following: //import your custom string file #import NSStringPrefix.h
NSStringPrefix *customURL = yoururl.com
NSString *baseUrl = baseurl.com
NSArray *yourarray = [[NSArray alloc] initWithObjects: @"one", @"two"]
if([customURL hasPrefixArray:yourarray withbaseURL:baseUrl])
{
//dowork
}
UPDATE
Define the variables in a global class.
#define companyOrSiteName @"Company X"
#define baseUrl @"http://www.example.com/" // Set base URL for site.
#define customUrlScheme @"example://" // Set custom URL Scheme for app.
#define openInModal [NSArray arrayWithObjects: @"contact-us.php",@"products/",nil]
#define openInSafari [NSArray arrayWithObjects: @"about",@"products/resources/download",nil]
#define twitterHandle @"Example" // Twitter username without the "@" symbol
#define kTrackingId @"UA-4564564-3" // Set Google Analytics iOS App Tracking code.
Upvotes: 1
Reputation: 681
NSArray *parts = [currentUrl componentsSeparatedByString:@"/"];
NSString *name = [parts objectAtIndex:1];
After this you can check if the string name is a element in pages array.
Upvotes: 0