rootpanthera
rootpanthera

Reputation: 2771

Using variables in Objective-C

I just want to open a webpage providing an URL. My code is:

 void openURL(char const *message)
{   

   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];
}

And the error I get is:

 cannot initialize a parameter of type 'NSString *' with an lvalue of type 'const char *'
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];

I am not familiar with Objective-C nor learning it. I just need to use this simple code in a project.

Upvotes: 2

Views: 350

Answers (2)

Tanvi Jain
Tanvi Jain

Reputation: 937

Try to convert char array to nsstring object first and then make url of that string. likebelow:- void openURL(char const message) {
NSString
s = [[NSString alloc] initWithBytes:buffer length:sizeof(message) encoding:NSASCIIStringEncoding]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:s]]; }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

One solution is to convert message to NSString, like this:

void openURL(char const *message)
{   
    NSString *messageStr = [NSString stringWithCString:message 
                                           encoding:NSUTF8StringEncoding];
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:messageStr]];
}

Another solution is to pass NSString (this wold require constructing NSStrings in all places where openURL is called:

void openURL(NSString *message)
{
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];
}

Upvotes: 3

Related Questions