tags:

views:

275

answers:

3

How would you make a button in cocoa when clicked open a web page?

+7  A: 

Assuming you mean opening the page in the user's default browser (not in a web view inside your app), see -[NSWorkspace openURL:]

smorgan
I see, can you give me an example of the code?
Joshua
From one of the samples listed on the page smorgan linked to: [[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:completeURLStr]];
Chuck
How would you link it to a button?
Joshua
Except if this is a remote webpage, you would use URLWithString, rather than fileURLWithPath:.NSURL is well documented if you need more information: http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html
smorgan
Put the call in your button's action method; the same way you make anything else happen when a button is clicked. If you aren't familiar with the basics of hooking up UI to code using interface builder, try a tutorial like http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/ObjCTutorial/01Introduction/01Introduction.html
smorgan
So I create an action, which I will link to the button, but what will I put in the .m file to explain the Action?
Joshua
That's where you call openURL: from.
Peter Hosey
+3  A: 

Google finds

http://www.edenwaith.com/development/tutorials/edenmath/workinginternet.html

fairly quickly.

Alternatively, follow the link provided by smorgan, and look at the cited example programs referenced within the Apple documentation. The OpenURL documentation specifically references "Related Sample Code" entries for NSOperationSample, ObjectPath, PredicateEditorSample, QT Capture Widget and VertexPerformanceTest, after all.

Stephen Hoffman
read the FAQ again Stephen.http://stackoverflow.com/faq
Keng
Eh? If you're asking for code (as was the questioner), then I know I missed the related examples section when I was first reading the Apple Cocoa documentation. That there's a veritable gold mine down there in that section wasn't obvious. To me. And quite possibly, others had not noticed that resource (why else would you ask for code when there are projects with example calls. Hence the pointer and the comment. (And ps: I didn't have SO "comment" rights back then.)
Stephen Hoffman
+4  A: 

Just like what Chuck said, look up this. For example, if I wanted to link to Google.com, You would do the following:

- (IBAction)goToLink:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString:@"http://google.com"]];
}
Daniel Kindler
I see, thanks very much!
Joshua
Says NSURLURLString is Undecalared. Why?
Joshua
I meant to put 'NSURLURLWithString Undeclared'. Why is this happening?
Joshua
Can you tell me why I am getting this error?
Joshua
Some help please!
Joshua
@Joshua make sure there's a space between NSURL and URLWithString
Jay Conrod