Search code examples
iosobjective-cnsurlnsstringencoding

Unable to create NSUrl from NSString always getting nil


NSMutableString *string = [[NSMutableString alloc]initWithString:
@"http%3A%2F%2Fsupport24hour.com%2Fworkplace2%2Fbuttler%2Fimage.php%3Fwidth%3D534%26height%3D256%26image%3Duploads%2Fdeals%2FdealImage%2Fdeal_1383005121_IGA+Logo.JPG"];

[string replaceOccurrencesOfString:@"+" withString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];

NSURL * url =  [NSURL URLWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Solution

  • one of my colleague faced the same problem , try below line of code . Hope your problem will be resolved

    NSMutableString *string = [[NSMutableString alloc]initWithString:
                               @"http%3A%2F%2Fsupport24hour.com%2Fworkplace2%2Fbuttler%2Fimage.php%3Fwidth%3D534%26height%3D256%26image%3Duploads%2Fdeals%2FdealImage%2Fdeal_1383005121_IGA+Logo.JPG"];
    
    string = [[NSMutableString alloc] initWithString:[[string stringByURLDecode] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    
    NSURL * url =  [NSURL URLWithString:string];
    
    NSLog(@"url = %@",url);
    

    Where stringByURLDecode is a category method used to decode URL and it goes like this

    - (NSString *)stringByURLDecode {
    
    NSMutableString *tempStr = [NSMutableString stringWithString:self];
    [tempStr replaceOccurrencesOfString:@"+" withString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
    
    return [[NSString stringWithFormat:@"%@",tempStr] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    }
    

    Best of Luck (y)