Make GET request through a Webview

Asked

Viewed 53 times

0

I have a problem trying to send a request via get for a Webview to open the contents of a page, when I pass the concatenated parameters an error occurs, I believe it is for encoding reasons this only occurs when I pass parameters with special characters, Could anyone assist me in this matter? Follow the code I’m using.

NSString *titulo = [listDictionary objectForKey:@"titulo"];
NSString *imagem = [listDictionary objectForKey:@"imagem"];
NSString *descricao = [listDictionary objectForKey:@"descricao"];

NSString *getString = [NSString stringWithFormat:@"https://meudominio.com.br/web.php?titulo=%@&image=%@&conteudo=%@", titulo, imagem, descricao];


getString = [getString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

NSURL *url = [NSURL URLWithString:getString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webview loadRequest:requestObj];
  • Can you report the error you are experiencing? Try using UTF8 encoding (Nsutf8stringencoding)

1 answer

1

I have a function for these cases. You need to convert the text of the values of the GET call to the so-called Percent Encoding, but the characters '&' and '?' are not included in this Objective-C conversion (remembering also that you need to choose the UTF-8 encoding in this function). Make an extension (Extension) of Nsstring and add the following:

-(NSString*)stringToWebStructure
{
    NSString* webString = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    webString = [webString stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
    webString = [webString stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"];

    return webString;
}

And then replace that:

NSString *getString = [NSString stringWithFormat:@"https://meudominio.com.br/web.php?titulo=%@&image=%@&conteudo=%@", titulo, imagem, descricao];


getString = [getString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

NSURL *url = [NSURL URLWithString:getString];

That’s why:

NSString *getString = [NSString stringWithFormat:@"https://meudominio.com.br/web.php?titulo=%@&image=%@&conteudo=%@", titulo.stringToWebStructure, imagem.stringToWebStructure, descricao.stringToWebStructure];
NSURL *url = [NSURL URLWithString:getString];

This is another important detail: you should not convert the entire URL, only the values of the arguments, after all the rest of the URL is already in an acceptable format.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.