Browsed by
Category: Apple

Run PHP scripts in native macOS app with Xcode & Swift

Run PHP scripts in native macOS app with Xcode & Swift

Developer Curiosity

Many, many years ago, as an open source PHP and WordPress developer, I had a system for testing arbitrary PHP as I honed my skills and learned new techniques. I had a file on my web server called test-php.php that did nothing but output the results of my code and would spend hours writing code, upload to server, switch to browser, refresh. This is how I learned the basics of regex, converted base64, tested operators, and refined my database access techniques.

I’m with Swift!

On a bored and underutilized day in 2012, I decided to figure out how to write an app to simplify the process. I had similarly written two apps previously, the first of which was a rip on a crazy flub by the Mitt Romney campaign when they released a campaign app called, “I’m with Mitt!” which would overlay Mitt Romney Oh ’12 campaign slogans on live photos. Hilariously, their developers failed to QC it thoroughly, ending up with a silly typo on the main overlay which draped the photos, meant to be shared socially using the app’s built-in functionality, with the slogans, “A Better Amercia” and “I’m with Mitt”.
forkme_right_darkblue_121621 Run PHP scripts in native macOS app with Xcode & Swift
That was not typo in my post. I know how to spell America. So, being smart like I am, I built an app that did the exact same thing. Except I misspelled “Mitt” as “Milt”. I called it “I’m with Milt” and overlookably misspelled something in every overlay.

Read More Read More

Parental Controls are a Perpetual Parental Annoyance

Parental Controls are a Perpetual Parental Annoyance

Parental Controls with Steam

Steam_icon Parental Controls are a Perpetual Parental Annoyance  According to Steam, I can either disable parental controls, anti-malware, anti-virus, and browser privacy settings, type in my root password, and give Steam unfettered access to control the operating system as if it were sitting at the computer using its fingers, or I just tell them they can’t play Portal 2.

2000px-Apple_logo_black.svg Parental Controls are a Perpetual Parental Annoyance  Apple’s Safari Brower

www.boyslife.com is a restricted site that requires an admin password to access.

YouTube is Strictly Bad About Restrictions

4481461680_4273d06822_b Parental Controls are a Perpetual Parental Annoyance  Even the most basic restrictions on YouTube block them from 75% of the Minecraft videos they want to watch.

Is Disabling Parental Controls the Only Option?

Read More Read More

There comes a point, I guess, no matter how young you feel, where you realize you’re old.

There comes a point, I guess, no matter how young you feel, where you realize you’re old.

My boys have their own computer where they play games I’ve installed which seem to not cross my boundaries for what’s ok for kids to play. One of the games I’m sort of on the fence about because it seems to bring out a lot of creativity, while also creating an unpredictable anxiety in them, is Minecraft.

So I limit their time with the game while I monitor their behavior surrounding their exposure to it. It’s not like it’s all that different from other games, but for some reason they get really into it and fight over who gets to play on the computer.

This means their computer gets lots of use. Which is cool, since it’s the laptop I bought back in 2008 that has been the bane of my professional life for at least 2 years. I put an SSD in it and 6 gigs of ram to buy it new life, so I’m glad it’s finding a useful retirement phase.

The thing is, though, my kids have never known or used a computer you turn off. The iPad and iPhones they’re used to just turn off when you’re done with them.

Without my guidance, they’ve discovered how to “turn off” the computer.

> Hit the mute button on the keyboard.
> Hit the power button on the monitor.

So I end up sitting here for much of the night after they go to bed half consciously trying to figure out why one of my devices is fans-ablaze until finally I realize that Minecraft taxes the shit out of that laptop and it’s been on since 8:00 with nobody even paying attention to Steve’s needs or intentions. (I think Steve is the Mincraft guy’s name…my kids call him Steve.)

I pick up the mouse, turn on the monitor, and Steve’s just standing there, staring into a wall or the sky or something. And the fans are at top speed trying to keep the processors and ram cool.

Command Q quits the game and within 30 seconds the fans whir down to silent. So, next step, after Ian’s potty trained, teach them how to quit a game on a computer that doesn’t just handle all that shit for you.

Computers that don’t need to be turned off, programs that don’t need to be quit, documents that don’t need to be saved, information that doesn’t need to be backed up, software that uses the same data source, no matter where you’re using it. That’s quickly making me feel old with these devices that were so transformative for me, so freeing, but are now so confounding to my kids.

Being conservative has its benefits

Being conservative has its benefits

I’m a huge nerd. I serve HariKari.com from my house using Mac OS X Server only because I love this technology. I love the pressure it creates for me to learn something I might otherwise not even be involved in.

The bloggers here might take umbrage. It’s been pretty smooth sailing, with the occasional sea-sickness, but nothing like this past week. So for me to have different goals from theirs – the spreading of democracy and the informing of the masses – I can see it being something I have to explain.

The site went down last week and, as has been the case before, I was sure that a reboot, or DNS change, or permissions issue, or unpaid bill was the root cause. But no such luck. Unfortunately, it turns out, my liberal policy of early adoption of new tech, ironically, is what took the site down.

I have an obligation to these guys to keep the site up. They don’t pay me, they don’t ask for 24/7 support, I’m a volunteer, and so are they. We’re a team of people who care about what we’re doing. That’s why this works.

Last week, however, I decided to upgrade to a developer preview of the software that HariKari.com is served with. It turned out to be a huge mistake because everything just stopped working and, due to it being pre-release software, only available to people who’ve signed a non-disclosure agreement, there’s no stackexchange.com thread to help you figure out what you did wrong.

In this case, I should have been more conservative. I shouldn’t have risked something as important as this blog is to my friends to satisfy my curiosity about emerging technologies.

But, as I started writing this mea-culpa, I came across some interesting realizations. First, I think there’s a lot of intentional conflation between being conservative when it involves imposing your own interests on those to whom you have a social obligation and being conservative to preserve your own investment in the status quo. In fact, the former strikes me as quite liberal.

Second, being considerate of how your needs might impose upon others doesn’t strike me as liberal. This is probably the same point I was making previously, but holding back your need to impose your beliefs on others seems quite conservative!

More personally, being conservative in my adoption of new technology has never benefitted me in the jobs marketplace. I’ve been an early adopter all my life and it’s served me well. Both socially and technologically, I’ve benefitted from forward thinking and adaptation.

Where being conservative has benefitted me is where I held back my own passions to make consideration for others. When I’ve been unsure that the risks I’m willing to take won’t work to the detriment of those to whom I have obligations, holding back conservatively has always been the right choice.

In this case, I didn’t. I mistakenly let my trust in my own techno-lust override my judgment and screwed over some people to whom I have not only a professional, but also a personal and emotional obligation.

For that, I apologize.

Harikari shutdown

Harikari shutdown

Greetings loyal readers. Harikari is back online. We can either blame the temporary shutdown on a new developer version of OS X that has some connectivity problems, or we can blame it on John Boehner. I am going with Boehner. Everything bad that happens now – I blame John Boehner.

Thanks to webmaster Tony and President Obama for getting it up and running again.

Better Native PHP Syntax Support in Xcode

Better Native PHP Syntax Support in Xcode

I’m a big fan of the Xcode IDE from Apple. Unfortunately, it is myopically focused on development for iOS and Mac OS X, using Objective-C. A long time ago, it was a lot more open. You could find a variety of plugins that would extend its functionality to include the projects you work with, such as PHP syntax support, in Xcode outside of the Apple software ecosystem. But for the past several years Apple has made it difficult to extend the IDE beyond their intended purposes. I’m mainly a backend PHP developer, but I have been a long-time Mac user. This puts me in the position of having second-rate tools for the biggest reason I use my computer. Yes, there are IDEs for Mac OS X that focus on PHP, but they’re all cross-platform and written in Java, which is, itself, a second class citizen on the Mac platform.

I’ve suffered through using Netbeans, Eclipse, and PHPStorm for years, all the while yearning for a grown-up IDE like Xcode to do my job. No longer! With Xcode 4, Apple introduced CodeSnippets that allow a user to not only save commonly used code snippets to an easily accessible palette, but we can tokenize the snippets and define the prefix text to which Xcode’s autocomplete feature will respond. Type “fore…” and if you have a snippet called “foreach”, Xcode will offer up the helpful autocomplete list with your snippet. Hit tab or enter and the snippet will be inserted at the cursor. Hit tab again and you’ll be guided through the snippet’s tokens, one by one, allowing you to fill in the blanks.

With this in mind, I went to work creating over 5,000 snippets to cover the entirety of the PHP language. See my github repo here: https://github.com/tonyjohnston/PHP-Xcode-Autocomplete Now I have native-like autocomplete for Xcode. I start typing “str” and here’s what I see:

Screen-Shot-2013-06-07-at-6.21.41-PM Better Native PHP Syntax Support in Xcode

I tap enter and this is what results:Screen-Shot-2013-06-07-at-6.23.58-PM Better Native PHP Syntax Support in Xcode

I type “if” and Xcode presents this:Screen-Shot-2013-06-07-at-6.25.17-PM Better Native PHP Syntax Support in Xcode

Arrow down to ifelse and tap enter:Screen-Shot-2013-06-07-at-6.26.30-PM Better Native PHP Syntax Support in Xcode

Each of those blue rectangular ovals is a tabable token, just waiting for you to enter your specifics, just like Xcode’s support for Objective-C. It’s a huge advancement in the arena of Mac PHP IDEs. It took me about 6 hours to put this whole thing together so I’m sure that it can get better. Feel free to fork my GitHub repo for PHP Xcode Support and help make PHP a first class citizen on the only great IDE for the Mac.

I spent half an hour on the “service chat” with AT&T and eliminated $20 worth of overpriced services I wasn’t using. Here’s the script…

I spent half an hour on the “service chat” with AT&T and eliminated $20 worth of overpriced services I wasn’t using. Here’s the script…

AT&T sales representatives are happy to assist you with your questions. AT&T sales representatives will not have access to your personal account. This service is provided to you under AT&Ts Terms and Conditions and Privacy Policy. 

You are now chatting with Lorena, an AT&T sales representative.

Lorena: Welcome to AT&T online Feature Sales. How may I assist you with your features today?
Tony: I’m only using about 10% of my data plan. How can I choose a cheaper plan?
Lorena: I’d be happy to help you with our features today, Tony. Which data plan do you have now?
Tony: Or, if it’s possible, how can I add data and device tethering so that I can drop my home internet and just tether to my phone?
Tony: It looks like I’ve got Data Pro 2GB LTE
Tony: for iPhone
Lorena: The tethering/hotspot data plan is the 5GB for $50 if you wanted to do that. If you want to lower your data plan, we do have the 300MB for $20 that you can switch to. You wouldn’t be able to tether/hotspot with your phone unless you have the 5GB.
Tony: hm. No, I guess that’s not a better option. I get unlimited data via my cable provider for $47.
Tony: so it’s $25 for 2gb and $20 for 300mb?
Lorena: That’s correct. The 2GB data plan is no longer available though so once you switch from it, you won’t be bale to get it back.
Tony: what is available now?
Tony: The only option I see is the one I currently have.

Read More Read More

How to run PHP scripts in Xcode Mac OS X applications

How to run PHP scripts in Xcode Mac OS X applications

Picking a starting point

I spent a lot of time looking around the web for instructions on how to execute PHP scripts in Xcode applilcations only to find a whole lot of nothing. I knew it could be done since there are several apps in the Mac App Store that allow you to interpret PHP on the fly, so I set out to do it without the help I believed I needed. It turns out to be one of the easiest things I’ve done in Objective-C.

There is an update to this post where I’ve done the same thing using modern Swift and incorporated a very basic syntax highlighter.

Swift PHP Runner

The first thing I did was to download the JavaScript Interpreter sample code from the Apple developer site for reference. It’s old code and doesn’t compile readily on a 64 bit system with the OS X Lion SDK, so to get it to run I had to change the target to fit my system as shown below. Xcode will also ask you if you want to update the code to current standards – go ahead and do that.

Screen-Shot-2012-04-19-at-11.11.23-AM How to run PHP scripts in Xcode Mac OS X applications

Getting Objective-C to execute PHP scripts

Screen-Shot-2012-04-19-at-3.41.52-PM How to run PHP scripts in Xcode Mac OS X applications  Next, I changed the code to skip the JavaScript interpreter and use PHP instead. This involves the NSTask Class from the Foundation Framework. Luckily the Foundation Framework is already included in the JSInterpreter sample code. While we’re talking about included Frameworks, you can go ahead and remove the reference to the JavaScript Framework now. To get rid of the red squiggly lines and error messages, delete the #import directive at the top of the MyController.m file along with all of the code inside the evaluateScript method.

Next, I searched for a way to run a command line script similar to “> php testing.php” that would allow me to execute a script and see its output. As always, Stack Overflow came to my rescue. I took the basics of the code there and went to (not very much) work.

First, I had to replace the NSTask LaunchPath with the php binary executable on my system, which is at /usr/bin/php.

Next I had to replace the arguments with the code I wanted to run, which was at ~/tonyj/Sites/harikari/test/testing.php – a script that simply echos “Hello world!” To keep from having to alter the existing code too much, I put in the whole path but left out the filename so that I could type it into the input field of the original application and have it executed when I clicked the button.

That’s it. I built and ran the application and I had a window with an input field and an output filed. I typed the name of my script into the input field and, ta-da!, “Hello world!” appeared in the output field.

A standalone application?

Next I wanted to see if I could make the whole thing a standalone application. This being my first attempt at writing a Mac OS X application in Xcode, I had no idea where to start. So I just went for it. I added my PHP binary to my application (File -> Add Files to JSInterpreter) and then added my script to the project. I wasn’t quite sure what the path was going to be for either of them in the application bundle, so I went back to Stack Overflow to find out about [NSBundle mainBundle] resourcePath] as a method for getting the path to the inside of your application, wherever it may be.

It worked!

With one caveat: I haven’t worked through all of the details yet, so I’m sure there are some dependencies in the PHP binary that my system provides in the place that PHP is looking for them. But I’m confident that it would not be difficult to find and eliminate or compensate for them.

Also, Objective-C doesn’t automatically wait for the return value from a task the way PHP does. And PHP is sometimes a little slow to respond. So you have to figure out how to make it wait around for a response from PHP and your script, especially if it’s a lengthy one. Once again, Stack Overflow helped me find information about the NSNotificationCenter. I don’t know much about it, but it basically notifies your code when the PHP output file is done loading.

Now I can load any PHP script into my application and send and receive messages to and from it. I might try adding MySQL tomorrow.

The code:

forkme_right_darkblue_121621 How to run PHP scripts in Xcode Mac OS X applications

-(NSString *) evaluateScript:(NSString*)scriptName
{
    NSTask *task = [[NSTask alloc] init];
    NSString *taskPath =
        [NSString stringWithFormat:@"%@/%@",
        [[NSBundle mainBundle] resourcePath], @"php"];
    [task setLaunchPath: taskPath];

    NSArray *args;
    NSString* scriptPath =
        [NSString stringWithFormat:@"%@/%@",
        [[NSBundle mainBundle] resourcePath], scriptName];
    NSLog(@"script file path: %@",scriptPath);
    args = [NSArray arrayWithObjects:scriptPath, nil];
    [task setArguments: args];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file = [pipe fileHandleForReading];
    [file waitForDataInBackgroundAndNotify];
    [[NSNotificationCenter defaultCenter]
 addObserver:self 
           selector:@selector(receivedData:) 
               name:NSFileHandleDataAvailableNotification 
             object:file];
    [task launch];

    NSData *data = [file readDataToEndOfFile];
    NSString *string =
        [[NSString alloc] initWithData: data
 encoding: NSUTF8StringEncoding];

    return string;
}

- (void)receivedData:(NSNotification *)notif {
    NSFileHandle *file = [notif object];
    NSData *data = [file availableData];
    NSString *str = [[NSString alloc] initWithData:data
 encoding:NSASCIIStringEncoding];
    NSLog(@"%@",str);
}

Altering the code

This is an example of how to type in the name of any file included in your project, but you may want to just execute raw PHP commands or fully integrate PHP into your app. To do this, just look at the line above where the args variable is set. You want your array to have filepath as its first element, then any arguments you want to have available in the argv[] array.

If you want to execute single PHP functions, your first arg will be “-r”, followed by the function as in the following example.

args = [NSArray arrayWithObjects:@"-r",@"is_array(array(1,2,3))", nil];
Apple TV 2.3 Finally Includes Video Playlists, 3rd Party Remotes

Apple TV 2.3 Finally Includes Video Playlists, 3rd Party Remotes

Here’s a quick note to update my ongoing struggle to ensure that my Apple TV doesn’t fall out of usefulness before its time. As you may remember I posted several months ago a wishlist for Apple’s next Apple TV update. It included some of the obvious things like responsiveness, performance, and video playlists. Unfortunately, none of these luxuries were included in the last update.

Apple TV 2.3, however, does actually seem to address many of the issues I pointed out in my last Apple TV post. The remote actually elicits an almost immediate visual response from the unit. There aren’t quite so many moments where I’m asking myself, “did that button press register?” It still happens, but I would say it’s quite less frequent now.

Two great features have been added with this update: 3rd party remote control support and video playlists.

Video playlists: Now you can play uninterrupted video through all of your day’s video podcast subscriptions. You can also set a video playlist to last through your New Year’s Eve party. Just create a playlist of videos on either a shared library or on your Apple TV’s main linked and synced computer.

This feature is great because now you can play each of your 2 or 3 minute podcasts from your favorite sources back to back as you turn to jello on the couch after a long day of hard brain stuff. You can create channels based on content and sit, motionless until every last one of those suckers has played.

3rd Party Remotes: Let your inner couch potato rejoice. Finally you can assign 6 of those extra buttons on ANY remote control littering your coffee table to the 6 functions of that little white remote that came with your Apple TV. Just enter Settings, Remotes, and start pushing buttons. It doesn’t matter which button you push on whatever infrared remote you have, as long as it doesn’t interfere with the main function of the device the 3rd party remote came with, you can repurpose the button for your Apple TV.

One sad note, Boxee was wiped out. I no longer have access to Hulu, Comedy Central, MySpace TV, and Torrents. And from what I’ve read, it’s not re-installable at the moment. However, I’d venture that most Apple TV users will enjoy the new features enough to make the update worth it anyway. While the Boxee crew will likely be hard at work creating a new installer and have you back on the Internet TV IV before the DTs have a chance to give you dead ceiling baby nightmares.

Also, I’ve got a few Boxee invites, so let me know if you’re interested in the comments.

Synergy – Dual Monitor Desktop Solution for MacBook Pro

Synergy – Dual Monitor Desktop Solution for MacBook Pro

 

synergy Synergy - Dual Monitor Desktop Solution for MacBook Pro

Have you ever been sitting at your desk with your laptop open, working away on your dual-monitor desktop setup and thoughtlessly tried to move your mouse from your desktop monitor straight over to your laptop? What about copying a URL to the clipboard of your laptop then jumped over to your desktop to try to paste it into an email? It doesn’t work, right?

Well now it can. Synergy is an open source project that allows you to do just that. Install it on your windows desktop and your MacBook, take a few minutes to configure it, and voila! You’ve just created the perfect dual monitor, multi-operating system desktop work environment. 

You can now seamlessly move your mouse monitor to monitor to laptop and copy from one operating system and paste into another.

In my own setup, I’ve connected the keyboard and mouse via bluetooth and the left-side monitor to the Windows XP box sitting under my desk, and the center monitor to the MacBook Pro. Running Synergy on the Windows box in server mode and client mode on the MacBook, I now have a fully integrated multi-monitor desktop and laptop combo.