Programmatically launching OS X's Contacts app showing a contact? - macos

Let's say that I've just created an ABPerson record and managed to save it in the user's address book. How do I programmatically open the default application which handles the address book (which most likely is Contacts but in some cases it might be Outlook or some other app) and show the new address book record I've just added?
Thanks in advance.

The addressbook URL scheme is able to show the person record or edit it:
ABPerson * aPerson = <#assume this exists#>;
// Open the Contacts app, showing the person record.
NSString * urlString = [NSString stringWithFormat:#"addressbook://%#", [aPerson uniqueId]];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:urlString]];
More information is in Address Book Programming Guide.

Here is my take using the Contacts app, and in Swift, written as an extension for CNContact. I expect most people are using Contacts in preference to AddressBook nowadays.
(CNContact's identifier is the same as ABPerson's uniqueId.)
func showInContacts() {
let path =
"/Users/someusername/Library/Application Support/AddressBook/Sources/05A62A31-9C1F-423F-A9F4-011E56EAAF29/Metadata/0A1F4FC2-7E01-4A40-92DE-840F8C84DE58:ABPerson.abcdp
var url = URL(fileURLWithPath: path)
url.deleteLastPathComponent()
url.appendPathComponent(self.identifier)// self is a CNContact
url.appendPathExtension("abcdp")
NSWorkspace.shared.open(url)
}
Contacts are in separate files buried at the end of a long chain of sub-folders in user's Library/Application Support. The file names are simply the contact's identifier plus an extension. You can save some typing by dragging one of them to your Xcode editor, surrounding with quotes, and maybe removing the last path component. As my app isn't for distribution that is enough for me; otherwise you will have to do some doctoring: the user's name will be in the second path component. I don't know the significance of the long ID number following 'Sources', whether it is user or system specific, but it is the only item in that subfolder, so you should be able to build a viable path programatically.

Related

macOS Apple Help Authoring - Anchors

I'm trying to make an Apple Help book for my macOS app that I'm ready to release. However, I am trying to make anchors work in my HTML. By Apple's definition:
"Anchors allow you to uniquely identify topics in your help book. When
a user follows a link to an anchor, Help Viewer loads the page
containing the anchor. ... You can also use anchors to load an
anchored page from within your application by calling the the
NSHelpManager method openHelpAnchor:inBook: ..."
Example from Apple: <a name="ArrivalTimesUsingStopID"></a>
In my Apple, I have an NSAlert which has the following code to display the help button so that when you click on it, it opens the specified anchor string.
alert.showsHelp = true
alert.helpAnchor = NSHelpManager.AnchorName(stringLiteral: "ArrivalTimesUsingStopID")
Running the code does display the help button and Mac Help does open, but to an error saying that the specified content cannot be found. Not sure why the anchors aren't working because I can access the Help Book if I go to the Help menu and open it from there.
Furthermore, Apple's document states:
The NSAlert, SFChooseIdentityPanel, SFCertificatePanel classes provide
help buttons for dialogs. To display such a help button and link it to
an anchor in your help book, use the methods setShowsHelp: and
setHelpAnchor: in those classes.
and the documentation for these properties in NSAlert state:
-setShowsHelp:YES adds a help button to the alert panel. When the help button is pressed, the delegate is first consulted. If the delegate
does not implement alertShowHelp: or returns NO, then -[NSHelpManager
openHelpAnchor:inBook:] is called with a nil book and the anchor
specified by -setHelpAnchor:, if any. An exception will be raised if
the delegate returns NO and there is no help anchor set.
...so I know that I am using these two properly.
I also understand that I need to create a .helpindex file every time I update my Apple Help book HTML documents. I'm using "Help Indexer.app" which is in the Additional Xcode Tools on developer.apple.com. I make sure that:
I have the option set to index all anchors.
Any HTML page with an anchor has <meta name="ROBOTS" content="ANCHORS"> in the header so anchors are indexed.
My Apple Help book plist file correctly points to the .helpindex file created by "Help Indexer.app".
But even with all of this, I cannot get it to open the Apple Help book to the correct anchor or even the Title page of my Apple Help book.
I've read
https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/ProvidingUserAssitAppleHelp/user_help_intro/user_assistance_intro.html#//apple_ref/doc/uid/TP30000903-CH204-CHDIDJFE
from cover to cover multiple times and I cannot find a solution or anywhere online.
I've also tried opening it manually, but it just opens to the same error saying the specified content couldn't be found with the following code:
let bookName = Bundle.main.object(forInfoDictionaryKey: "CFBundleHelpBookName") as! String
NSHelpManager.shared.openHelpAnchor("ArrivalTimesUsingStopID", inBook: bookName)
Using nil for the inBook parameter doesn't work either:
NSHelpManager.shared.openHelpAnchor("ArrivalTimesUsingStopID", inBook: nil)
Any ideas?
I'm not sure if this is the answer at this point, but it is an answer and one that seems to do the trick. I wasn't able to get the helpAnchor in the Alert to work, but using the help delegate, the method outlined below works.
I started out my day trying to open the Help Book to a simple anchor. I'm sure this used to work using the NSHelpManager in the past, but it does not appear to in recent versions of the OS.
Watching the console while opening my under-development App's help book resulted in the following:
Opening URL help:openbook=%22com.ClueTrust.Cartographica.help*1.5.2d1%22 with application <FSNode 0x6000006a1b40> { isDir = y, path = '/System/Library/CoreServices/HelpViewer.app' }
Opening to my anchor using NSHelpManager resulted in:
Opening URL help:anchor=SpatialJoinOperation%20bookID=%22com.ClueTrust.Cartographica.help%22%20appID=%22com.ClueTrust.Cartographica%22 with application <FSNode 0x6000006a8260> { isDir = y, path = '/System/Library/CoreServices/HelpViewer.app' }
And, it didn't result in opening to my anchor.
I tried appending the *<version> to my URL:
Opening URL help:anchor=SpatialJoinOperation%20bookID=%22com.ClueTrust.Cartographica.help*1.5.2d1%22%20appID=%22com.ClueTrust.Cartographica%22 with application <FSNode 0x600000682c20> { isDir = y, path = '/System/Library/CoreServices/HelpViewer.app'
Looking deeper into the Console, though, I noticed that this is definitely triggering a network request and there's an unsupported URL coming back.
It's not clear to me if help:anchor=... does not function any longer, but I did find a relatively easy, but annoying way around the problem.
Anchors within help will definitely be opened when using a help: URL that is formatted like a file: URL and contains an anchor; and they will open to the correct anchor location.
This requires locating the specific help book and HTML file so that you can specify precisely where to open.
NSURL *helpBookURL = [NSBundle.mainBundle URLForResource:#"Cartographica" withExtension:#"help"];
NSBundle *helpBundle = [NSBundle bundleWithURL:helpBookURL];
NSURL *helpPageURL = [helpBundle URLForResource:#"Spatial_Join" withExtension:#"html"];
NSURLComponents *urlParts = [NSURLComponents componentsWithURL:helpPageURL resolvingAgainstBaseURL:NO];
urlParts.scheme=#"help";
urlParts.fragment=#"SpatialJoinOperation";
NSURL *finalHelpURL = urlParts.URL;
[NSWorkspace.sharedWorkspace openURL:finalHelpURL];
Basically:
Get the URL for the help book (need to do this in a way that gets it from the resource path, hence we're using NSBundle)
Locate the page containing the reference based on prior knowledge (in this case Spatial_Join.html is our filename, so we have the bundle look for it by name and extension.
Use the NSURLComponents interface to mutate the NSURL by changing the scheme from file to help and adding our achor in the fragment.
Finally, open the newly-created URL
It's not pretty, but it does appear to be effective and safe, at least in a non-sandboxed macOS App under 10.15.
Note that I could make some assumptions here about the help book name, but for illustration purposes this seems more clear, and because of the way resources work, it's not clear that those assumptions about the names would be appropriate in all situations.
My final result was this helper method:
- (void)openHelpPage:(NSString*)pageName anchor:(NSString * _Nullable)anchor bookName:(NSString * _Nullable)bookName
{
NSURL *helpBookURL = [NSBundle.mainBundle URLForResource:bookName withExtension:#"help"];
NSBundle *helpBundle = [NSBundle bundleWithURL:helpBookURL];
NSURL *helpPageURL = [helpBundle URLForResource:pageName withExtension:#"html"];
NSURLComponents *urlParts = [NSURLComponents componentsWithURL:helpPageURL resolvingAgainstBaseURL:NO];
urlParts.scheme=#"help";
if (anchor)
urlParts.fragment=anchor;
NSURL *finalHelpURL = urlParts.URL;
[NSWorkspace.sharedWorkspace openURL:finalHelpURL];
}
Call site syntax is:
// to specific anchor on a page
[self openHelpPage: #"Spatial_Join" anchor: #"SpatialJoinOperation" helpBook: nil];
// to specific page
[self openHelpPage: #"Spatial_Join" anchor: nil helpBook: nil];
I tried getting the help bundle with [NSBundle bundleWithIdentifier:] using the help bundle ID, but that returned nil. However, [NSBundle URLForResource:withExtension] will take a nil argument for the resourceName and get the first item that matches the extension. In my case (and I believe many) there is only one help resource, so this allows for a method that doesn't require knowledge of the Application's help book name.
I was finally able to get this working in a sandboxed application.
If you're using a Help button directly, you can use something like:
#IBAction func helpButtonAction(_ sender: Any)
{
if let bookName = Bundle.main.object(forInfoDictionaryKey: "CFBundleHelpBookName") as? String {
NSHelpManager.shared.openHelpAnchor("MY_ANCHOR_HERE", inBook: bookName)
}
}
If you're using an NSAlert(), you can use its help button with an anchor this way:
let alert = NSAlert()
...
alert.showsHelp = true
alert.helpAnchor = NSHelpManager.AnchorName("MY_ANCHOR_HERE")
A few things I learned the hard way:
Make sure your HTML page for your Help Book has a the proper setup for an anchor with:
<meta name="robots" content="anchors"> in the <head> section as well as a proper header tag in the fashion of:
<a name="MY_ANCHOR_HERE"></a> in your <body> section.
Make sure you use "Help Indexer.app" to index your Help Book. I found that it will not work unless you index your Help Book using this app. This app can be downloaded from developer.apple.com under More Downloads. They usually release a new version with every Xcode update. You want to look for "Additional Tools" and the specific indexer app will be located in
Additional Tools > Utilities > Help Indexer.app
Additionally, macOS does not like when you have multiple Help Books. This means, multiple copies of your Application on your Mac no matter where they reside. This could be in your Debug folder and your Application folder as your most common places. I found that deleting the copy in my Applications folder usually helps macOS not get confused when opening a Help Book. I have also found it to open up older versions of the Help Book so it's best to make sure you only have once copy of your app on your Mac when debugging help books.
But other than that, they should open just fine with simply an Anchor string and a few lines of code depending on how you display your Help button!

XCode: Additional localization of only one button

After a long long time, I added another button to my apps dialog. I had localized strings implemented. So I found a similar one like
/* Class = "NSButtonCell"; title = "Keep number"; ObjectID = "2yE-rM-5Sn"; */
"2yE-rM-5Sn.title" = "Nicht umnumerieren";
in file "Main.strings (German)". Unfortunately I forget, how I got there. I did the entire translation in one step in one night. Now I only need to get one new translation for the newly added button.
Any hint how to do this?
Select your project name (1.), in my case Timebooking. Maybe the application is selected instead in Targets and you have more options but not localization. Then select Use Base Localization (2.). It should create the English Main.strings file when you add English. There you can add the proper translation. HTH.

How can you save a users input in an app

I am creating an app based on the functions of tinder.... if you like the word (created from a random generator) you swipe right and it stores it in a word bank for the user to go back to later on.
I am very new to Xcode and swift, What is the best way to go about storing the users input within the app?
Image of the layout of the page
You can use NSUserDefaults.
// Set
// forKey is the unique value to access the object you have saved
NSUserDefaults.standardUserDefaults().setObject("value", forKey: "key")
// Get
NSUserDefaults.standardUserDefaults().stringForKey("key")
So for example, when you want to save a variable called "score", do:
NSUserDefaults.standardUserDefaults().setObject(\(score), forKey: "key")
When you want to get this value:
let score = NSUserDefaults.standardUserDefaults().stringForKey("key")
There are several different types of defaults you can use, I have used setObject in this example.

How to give permission to certain users to see a view based on Parse user type property?

assume that i have two types of users: students and instructors. How can I be able to give permission only to instructors to go to some different views than students, for example
ObjectID UserName Password Type
------- -------- -------- ------
8uJ03j7 user#1 *** student
2835ruJ user#2 *** instructor
2835JhL user#3 *** student
Let's say we have an app for school, students can log in and see just their grades, whereas instructor can enter data and modified.
i was asking this question because as far as i know you cannot have two Uses Log in class in Parse.com that is why i wanted to make distinguish between two different types of users.
thanks
I interpret your question differently than MannyFle and ismailgulek. My interpretation: Based on what type of user is logging in, you want the app to automatically direct them to different views for instructors and students. No buttons to hide etc.
To achieve this, you can do the following in your AppDelegate:
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user {
NSString *userType = user[#"type"];
if ([userType isEqualToString:#"instructor"]) {
self.window.rootViewController = instructorViewController;
} else {
self.window.rootViewController = studentViewController;
}
[self.window makeKeyAndVisible];
I'm sure you've already implemented didLogInUser in your appdelegate. Do the check for usertype there. There is no need to use a singleton, as [PFUser currentUser] will be available to you anywhere in your app.
You will of course need to initialize the right instructor/studentviewcontrollers inside the if statement, before setting it as rootViewController.
Do not try to prevent any user from logging in. I think it is a very bad way of controlling anything. You can extend PFUser class and add an extra field like type and do any control after the user login.
What you can do here is hide the button that pushes the view that only instructors can see, if the user is logged in is of type student.
In the view that has the button that pushes the view that only instructors can use do this:
In the .h file create a property for the button that pushes the view like so:
#property (nonatomic,strong) UIButton *buttonThatPushesInstructorView;
In the .m file:
In the viewWillAppear method of the view do the following check:
if ([[[PFUser currentUser]objectForKey:#"type"]isEqualToString:#"Instructor"]) {
_buttonThatPushesInstructorView.hidden=NO;
}else{
_buttonThatPushesInstructorView.hidden=YES;
}
This way, when the view loads, the button that pushes the instructor view will only be accessible to the users of type "Instructor".
Hope it helps!

Prefill email content with NSButton hyperlink

I was wondering how I could, or if it's even possible to, prefill an email message's content when you click an NSButton, so far I open up the default email client but I want to prefill the body of the email and was wondering how I'd do that. Below is the current code:
-(IBAction)openEmail:(id)sender {
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:#"mailto:domain#domain.com"]];
}
The "mailto" URI scheme supports this: http://en.wikipedia.org/wiki/Mailto
Send email
Rather than forcing a user out of your app, why don't you use MFMailComposeViewController to present the standard message composition window?
MFMailComposeViewController conveniently also has methods to set the message body and just about anything else you would like.
UPDATE: Oops, I misread "NSButton" as "UIButton" - what I wrote above only applies to iOS. Using the mailto: additions is the correct approach AFAIK on OS X.

Resources