开发者

Declare an NSString With Format Specifiers and use it as a URL to open in UIWebview

开发者 https://www.devze.com 2023-01-30 07:57 出处:网络
I have an int containing a number. I am wanting to declare an NSString so I can use use format specifiers when assigning a value to it.

I have an int containing a number. I am wanting to declare an NSString so I can use use format specifiers when assigning a value to it.

I thought it might be something like this:

NSString[NSString stringWithFormat] myString;

myString = [@"http://myurl.com/%d",myInt];

I gather this is not the case, so question one is: How do I declare an NSString that can handle format specifiers and then assign it a value using format specifiers? The purpose of this NSString is to hold a URL, exactly like the second line above.

Question two is, How do I then use this string as a URL to open in a UIWebView? I assume I use something like this:

[webView loadRequest:

Sadly, this is as far as my knowledge stretches. Is there a way I can tell my UIWebView (webView above) to use the NSString with the URL I mentioned earlier?

I intend on havin开发者_开发技巧g the NSString as a global variable, as it will be assigned it's value inside a C function. And 'webView' will use it inside a (what I think is a) method. All of this code is in the same file, the Delegate.m file. It is all executed on launch of the application.


Your string should look like this:

NSString *myString = [NSString stringWithFormat:@"http://myurl.com/%d", myInt];

What you missed: adding the * to indicate a pointer, and thinking that you had to/could first state that the string would have a format and then later state the format. It all happens at once, creating the string with the specified format.

Edited to add NSURL

To create a url you're creating an object of class NSURL, like this:

NSURL *myURL = [[NSURL alloc] initWithString:myString];

And then you create the url request:

NSURLRequest *request = [NSURLRequest requestWithURL:myURL];

And finally, tell your webView to load the request:

[webView loadRequest:request];


For your first part:

NSString *myString = [NSString stringWithFormat:@"http://myurl.com/%d", myInt];

Then, based on a tutorial from iphonesdkarticles.com:

//Create a URL object.
NSURL *url = [NSURL URLWithString:myString];

//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
[webView loadRequest:requestObj];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号