Search code examples
objective-cnsstringnsarrayprefix

Check if NSString hasPrefix that is contained in NSArray


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?


Solution

  • 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.