Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective - C stringByAddingPercentEncodingWithAllowedCharacters not working

I have a URL like so ANC & SHO.pdf

when I encode the URL like so:

NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

now when I use this URL it does not work and I have a feeling it has to do with the & because when I tried another file, it worked perfectly I was able to load the PDF, but with the file with & I was not.

What Am I doing wrong?

Here is the output of escapedString

escapedString   __NSCFString *  @"Ancaster%5CANC%20&%20SHO%20-%20Laundry%20Closets%20to%20be%20Checked.pdf" 0x16ea33c0

I then use that to call a method:

NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:@"%@",escapedString]];

Here is the method:

-(NSArray *)GetPDFFileData:(NSString *)PDFFile
{
    NSString *FileBrowserRequestString = [NSString stringWithFormat:@"%@?PDFFile=%@",kIP,PDFFile];
    NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
    NSURLResponse* response = nil;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if(data == nil)
        return nil;
    NSError *myError;
    NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
    return tableArray;
}
like image 706
user979331 Avatar asked Sep 28 '15 13:09

user979331


1 Answers

[NSCharacterSet URLHostAllowedCharacterSet] contains characters below:

!$&'()*+,-.0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~

which contains '&', so

NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

won't escape '&' for you, then it's not URLEncoded.

see the question about how to url encode a string.

like image 159
Hong Duan Avatar answered Sep 28 '22 04:09

Hong Duan