I'm pretty new to Objective C in general...

I'm wondering how I can use a *variable in the view controller, and add it onto the web view URL. Bellow is a UIWebViewer, It loads "site.com/something.php"... Along with that I would like for it to addon to the URL "?uuid=(UUID Variable here)".

Sorry... I'm more used to PHP/Perl coding where you can just throw in "$uuid"... Thanks,

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *UUID = [[NSUUID UUID] UUIDString];
    NSURL *myURL = [NSURL URLWithString:@"http://www.site.com/something.php?uuid="];

    NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];

    [myWebView loadRequest:myRequest];
}
有帮助吗?

解决方案

It's very simple you just need to create a property to assign whatever value you want to it

ViewController.m

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *uuid = [[NSUUID UUID] UUIDString]; // Convention says that UUID should uuid

    // All we need to do now is add the uuid variable to the end of the string and we can do
    // that by using stringWithFormat:
    NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.site.com/something.php?uuid=%@", uuid]];

    NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];

    [myWebView loadRequest:myRequest];
}

Check the documentation of NSString and the class method stringWithFormat:

其他提示

Here's what you're looking for:

NSString *UUID = [[NSUUID UUID] UUIDString];
NSString *urlstr = [NSString stringWithFormat:
    @"http://www.site.com/something.php?=%@", UUID];
NSURL *myURL = [NSURL URLWithString:urlstr];

NSString's stringWithFormat: method allows you to build strings from literal strings and varaibles. Variables are added to the literal string using format specifiers. Most of the format specifiers are the same as all the other C-based languages, %d for integer types, %f for floating types, %c for char, etc.

In the case of Objective-C, the %@ is used as the place holder for objects that respond to the description selector, which returns a string. (In the case of an NSString, it just returns the string itself, but you'll notice that you can put lots of other types of objects in here too... in fact, every object that inherits from NSObject has a default description method).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top