iOS8 Simulator – Documents Directory

Update 8.1.3: Someone at Cupertino just can’t make up their mind. With the release of 8.1.3 the path for the documents directory changed yet again from:

~/Library/Developer/CoreSimulator/Devices/<SIMULATOR YOU WANT>/data/Containers/Data/Application/<APP YOU WANT>

to,

~/Library/Developer/CoreSimulator/Devices/<SIMULATOR YOU WANT>/data/Applications/<APP YOU WANT>

 tl;dr: Download the app. Run it to open the most recent application’s documents directory.

Upto iOS 7.1, the iOS simulators were located under

~/Library/Application Support/iPhone Simulators/

where you would be presented with a list of all the simulators you used. You can read more about it here. iOS 8 changed the directory hierarchy of the Simulator Devices and its Documents directories. Simulators are now located at

~/Library/Developer/CoreSimulator/

But there is another surprise. Instead of being presented with a human readable list of simulators like this,

Screen Shot 2014-11-28 at 3.24.45 pm

we now get gibberish

Screen Shot 2014-11-28 at 3.27.33 pm

Apparently, Apple thinks simulator names are too confidential to reveal to app developers. (before you get your chaddi in a ganth, I am just kidding. I am sure there is some perfectly reasonable explanation for this) Basically, we now have folders with UUIDs for names that we can’t map to anything. Assuming you are only interested to get into the device simulator you were most recently working with, a workable solution is to sort them by modified date in list view. Screen_Shot_2014-11-28_at_3_38_25_pm

In my case I can safely assume that 7B2CF1B3-1820-4313-B010-A4CCD4764D10 is actually simulator folder for iPhone 6 plus – 8.1 that I was just testing.

Next – Locating the Applications

Locating the application is another run through the maze. Inside your simulator folder you will find a structure like this

Screen Shot 2014-11-28 at 3.44.01 pm

The applications are located under

/data/Containers/Data/Application/

Here you can again sort the list by ‘Date Modified’ to get you most recent app on the top. The rest of the structure remains unchanged. So now you can just create an alias (shortcut) on you desktop and… STOP. YOU CAN’T! Because on each run of your app, the directory name for your app changes.. wow! You will have to do a circus everytime you need to inspect the documents directory of your current app. Unless you want to be awesome that is. And you can do that by writing a script, which

  • Navigates to the CoreSimulators/Devices directory
  • Sorts the results by ‘Data modified’
  • Picks up the latest one.
  • Navigates to ../data/Containers/Data/Application/
  • Sorts the results again
  • Picks up the latest one.
  • opens that directory in Finder.

You can find my script here if you want a guide, other wise just go for the directly executable app –

Download Executable App

Like other script apps the best way to use this app is to put it in some folder and just forget. You can launch it directly from spotlight every time you want to open the Documents directory.

YouTube iOS Framework

It’s almost 2015 and while we are close to the hoverboard dream, but integrating YouTube API still seems to be stuck in 2012. Starting iOS 8, we have full(almost) support for Frameworks and I think a service like YouTube is a perfect fit. Although Google seems to be taking its own sweet time to release one, here is something you can work with in the mean time.

It’s a Framework which bundles the libGTLTouchStaticLib.a provided by google-data-api along with the resources, framework and other files and settings required.

Frameworks are only available on iOS 8. If you are targeting a previous versions this link will be helpful.

Also, this is still a work in progress so there are a few limitations

  • This framework targets an actual device, and will not work on simulator. I am trying to generate a universal Framework but the GTL project form Google just does not give me a universal binary… very frustrating :(
  • I was not able to bundle the required .xib file as a part of the framework, so you will need to add that manually.

First you need to set up your app on Google Developer Console. If you need help regarding this, follow the Step 1 here.

Next download the Framework zip from this link or from GitHub. Inside this zip you will find:

  1. YouToobAPI.framework: This is the framework which contains all the google data API code. It also contains a helper class, YouTubeHelper, written by me to work with the google API. To take a look at the class and its implementation you can download the files here.
  2. GTMOAuth2ViewTouch.xib: This xib is a part of the google API. Ideally this should have been a part of the Framework, but at the moment I just could not find a way to do that.

Ok so now we have everything we need, lets test this out.

Create a new project in Xcode. Lets go for a simple Single View Application template.

1. New Project

Next, create a group for the framework and xib in you project and drag-drop these files into this group. Make sure you select the ‘copy if needed’ checkbox.

2. Add files

Go you your project settings and select the target. In the general tab, you will see our framework listed under the ‘Linked Frameworks and Libraries’ section. Thats good, but we also need to tell Xcode to treat it as an Embedded Binary. So click the ‘+’ button under ‘Embedded Binaries’ and select the framework.

3. Add as embedded binary

4. Added embedded binary

Try a build now, if all went well we should not have any errors. This is about it. Our project is ready to start talking to YouTube service. Currently the only usable class exposed by our Framework is YouTubeHelper. But for the sake of this tutorial and most common tasks, that is sufficient.

Go to the view controller .h file and

#import <YouToobAPI/YouToobAPI.h>

This will also expose the YouTubeHelper class to your view, you don’t have to import it separately.

Also make your view controller conform to the YouTubeHelperDelegate protocol.

@interface ViewController : UIViewController

Next we need to implement the protocol methods and start taking to YouTube service.

In your view controller, .m, create a property for YouTubeHelper.

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) YouTubeHelper * youtubeHelper;
@end
@implementation ViewController
...

We can initialise this property in viewDidLoad:

self.youtubeHelper = [[YouTubeHelper alloc] initWithDelegate:self];

Next we need to implement all the required delegates:

- (NSString *)youtubeAPIClientID {
    return @"YOUR_CLIENT_ID";
}

- (NSString *)youtubeAPIClientSecret {
    return @"YOUR_CLIENT_SECRET";
}

- (void)showAuthenticationViewController:(UIViewController *)authView {
    [self.navigationController presentViewController:authView animated:NO completion:nil];
}

- (void)authenticationEndedWithError:(NSError *)error {
    if (error) {
        NSLog(@"Auth failed with error: %@", error.description);
    }
}

Ok, we are all set up. From here you can start calling the methods in YouTubeHelper.

The first thing you will need to do is authenticate. Once that is done, you can be sure your app is communicating successfully with the API. Add a button to your view controller and in its selector call:

[_youTubeHelper authenticate];

You will notice that we are presenting the auth view though navigationController. Either you can change that or since we are using the ‘Single View Application’ template, we will need to embed our view controller in a  navigation controller. Open the storyboard, select your view controller.

5. Embed in navigation

Go to Editor > Embed In > Navigation Controller. This should make your view controller a child of a navigation controller.

Screen Shot 2014-11-18 at 1.01.32 pm

Ok now go ahead the test the authenticate function. You should be presented with a Google Sing In view.

For more functions of the YouTubeHelper class, like uploading a video, follow Step 4 here.

Quickly toggle Invert colors on OS X

tl;dr — download the app here.

(If you are on a slow machine, this may not work for you. But fear not, read on and you can build one that does.)

Some times,

DarkMode

just make a lot more sense to me than,

NormalMode.

If you have times like these too, OS X has an Invert colours option. Unfortunately it is buried layers inside System Preferences.

I need to switch between the modes often, depending on the kind of work I am doing. So I wrote an executable script (another word for an app) which can be run directly from spotlight.

invert_execution

Download the app from here. Place it anywhere on your system you want (provided that location is indexable by spotlight). You can be creative and rename the app anything you want. Just make sure that name is unique enough to come up on top in spotlight.

Since this app momentarily takes control of your system, the first time you try to execute it you will be asked to set permission for it. Open System Preferences > Security & Privacy. Here you will see the app listed.

  • Trust me
  • Unlock preferences
  • Check the app

Screen_Shot_2014-11-14_at_10_59_24_am

Unless you do not trust me, this should do it, go ahead and have fun. If you are suspicious of me, lets build one together :]

Launch ‘Script Editor’. This is the IDE we will use to write, compile and execute our script.

First, lets try and get our script to open the System Preferences window and navigate to Accessibility screen. Type in this code:


tell application "System Preferences"

activate

set the current pane to pane id "com.apple.preference.universalaccess"

end tell

Hit the play button on top to execute the script. Unless you had a monkey on your keyboard, this should open the system prefs and navigate to Accessibility(historically referred to as universal access) screen.

Next, lets look for the ‘Invert colors’ checkbox and toggle it.


delay 0.1

tell application "System Events"

tell process "System Preferences"

if (exists checkbox "Invert colors" of window 1) then

click checkbox "Invert colors" of window 1

end if

end tell

end tell

You will notice we put up a delay, this gives time for OS to actually finish launching System Preferences.

In case you are on a slow machine you may want to change this to a higher value.

Run it again, if everything goes as planned, you should see your world with inverted colours now. But we still have the system prefs open. Lets add code to close that as well.


tell application "System Preferences"

quit

end tell

 

The script is now ready, all we need to do is create an Application from it. In Script Editor, select File > Export… Give your app a name. Under File Format change ‘Script’ to ‘Application’. Done.

If you modify this script to do other cool things with the system prefs, do let me know.

Creating a OS X menubar only app

I just love small utility apps that sit in my mac’s menubar and provide some useful functionality. I recently updated to Yosemite beta and found the awesome ‘Dark Mode’. Since I also use a dark theme in Xcode while coding, this felt perfect. To switch on the Dark mode, there is a setting under System Prefences-> General -> Theme. Or you can enter commands in Terminal. Hmmmm… really?? Can’t I just have a switch in the menubar? Yes you can, but you have to build it yourself. (or just download it from here) So lets build a menubar app that you click once to switch to Dark Mode and again to go back to the loser mode :P (I am not a OS X developer, so my code might not be optimal, but dammit it gets the work done) Create a new Xcode project: step 1 Start by creating a new project, under OS X, select Application -> Cocoa Application Next, give it a cool name. 2 And there you have your mac app, run it! 3 So here we have an app that shows a blank window and a menu but no menubar item, exactly the opposite of what we wanted, great! Delete the menu and window Open the MainMenu.xib and delete the NSMenu and NSWindow that we don’t need. 4 Run the app again. Declare as agent Better… but we still want to get rid of the dock icon and the Menu. To do this we need to define our app as an “agent”. Open the Info.plist file and add a row. The key is “Application is agent (UIElement)” and change its value to YES. 5 NOW run the app! Where is the app? To be sure the app is actually running you can check it in the activity monitor -> search for your app name. There it is, ninjamode indeed. 6 Ok so now we want to have a little button in the menubar that our app can get user input from. First things first, we need a great icon. The icon can be a png file, you can get something free from flaticon.com, or just use this for now. You might need to resize your icon to fit into the menubar, a height of around 20 should be fine. Add the png to your project. Create the button Now we need to create the button itself. Open the AppDelegate.m. The interface will already have a property called window. We will need a couple more: @property (strong, nonatomic) NSStatusItem *statusItem; @property (assign, nonatomic) BOOL darkModeOn; The ‘statusItem’ is the menu button itself and the boolean ‘darkModeOn’ is used to keep track of the current mode. In the ‘applicationDidFinishLaunching’ lets add the code to create a button and add it to the menu bar. self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; _statusItem.image = [NSImage imageNamed:@"switchIcon.png"]; The first line requests a ’NSStatusItem’ from the systemStatusBar. In the second line we provide an image to this button. Run the app now. 7 Capture the click So there we have it, our apps button sitting with the system menubar items. Next lets capture the button click event. Add this code in ‘applicationDidFinishLaunching’ method. [_statusItem setAction:@selector(itemClicked:)]; We will also need to implement its selector: - (void)itemClicked:(id)sender { NSAlert * alert = [NSAlert alertWithMessageText:@"Bat signal acknowledged" defaultButton:@"Alright!" alternateButton:nil otherButton:nil informativeTextWithFormat:@"NSStatusItem was clicked"]; [alert runModal]; } To quit the app we can use: [NSApp terminate:self]; (more on this later)

Get the complete code here: https://github.com/nirbhayg/NinjaMode/tree/master

This is basically how you create a menubar only app. In rest of the post we write code to implement the Yosemite’s Dark mode switch. We will need a method to determine what the current mode is: - (void)refreshDarkMode { NSString * value = (__bridge NSString *)(CFPreferencesCopyValue((CFStringRef)@"AppleInterfaceStyle", kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost)); if ([value isEqualToString:@"Dark"]) { self.darkModeOn = YES; } else { self.darkModeOn = NO; } } CFPreferencesCopyValue is a function for reading some system preferences value. We use it to find the value for key ‘AppleInterfaceStyle’ which tells us wether the current mode is Dark or Light. We will call this and the end of the applicationDidFinishLaunching method to get the current state. [self refreshDarkMode]; Next we need to replace the code under itemClicked: method to actually switch the mode. - (void)itemClicked:(id)sender { _darkModeOn = !_darkModeOn; //Change pref if (_darkModeOn) { CFPreferencesSetValue((CFStringRef)@”AppleInterfaceStyle”, @”Dark”, kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); } else { CFPreferencesSetValue((CFStringRef)@”AppleInterfaceStyle”, NULL, kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); } //update listeners dispatch_async(dispatch_get_main_queue(), ^{ CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(), (CFStringRef)@”AppleInterfaceThemeChangedNotification”, NULL, NULL, YES); }); } We start by toggling the darkMode. Then depending on its value, we either set AppleInterfaceStyle to Dark or NULL. We use the CFPreferencesSetValue function to accomplish this. After we are done updating the value we need to notify all the interested listeners, in this case the OS itself. We use CFNotificationCenterPostNotification to do this. Now our app is functional. But there are still a couple of things missing. Firstly, you will notice that the icon does not look quite right in dark mode. So add this line after we provide image to our statusItem: [_statusItem.image setTemplate:YES]; This tells the OS that the image contains only black and clear pixels. This allows OS to make changes to this image. Screen Shot 2014-10-10 at 11.28.30 am Second thing we need is a way to quit the app. Since our app does not have a menu or a dock icon, it is difficult for the user to quit the app. One way they can do it is through Activity Monitor. Additionally we will allow the user to quit the app on a command-click. Inside the itemClicked: method add these lines at the top: NSEvent *event = [NSApp currentEvent]; if([event modifierFlags] & NSControlKeyMask) { [[NSApplication sharedApplication] terminate:self]; return; } Ok the app is basically ready for use. To export the app you can do Product -> Archive. Alternatively you can open the Products directory in Finder and copy the app from there.

Quickly launch iOS simulator and open simulator directory (iOS 7)

For iOS 8, go here.

As a developer we often need to get into our applications documents directory to see whats going on. It can be quite tiresome to locate this directory every time, specially because it is hidden! For those who do not know, the folder for simulator is located in your hidden ‘Library’ directory inside the home folder.

~/Library/Application Support/iPhone Simulator/

Here, you will find directories for different simulator versions you have run like 6.1, 7.1, 7.1-64 etc. Inside you need to navigate to the Applications directory and locate the application you are working with. Since the application directories do not use the application name as directory names, this can be a bit confusing. The easiest way is to just sort the folder by Date Modified. Screen Shot 2014-08-11 at 3.06.51 pm Most commonly we create a shortcut or ‘alias’ and put it on the desktop. Although its much better than having to navigate to this folder every time, it’s still inconvenient at times navigate out of Xcode, go to desktop and open this directory. A much easier way for me is a shortcut I can run through spotlight. b19ff

You can use this link to download an executable file that will open the simulator folder.

Another thing we often need is to launch the iOS Simulator itself. For this we need to run Xcode, then find a project that will run a simulator and run the project. The simulator software too is hidden inside the Library directory and further more, it does not get listed in spotlight searches by default.

There is another little app that can help you launch the iOS simulator right from your spotlight without the need to open Xcode.

b19m4

Quickly show/hide hidden files on mac

The most common way to show the hidden files and folders on a mac is via the terminal. Although it gets the job done, its a tedious process requiring me to:

  • Fire up the terminal
  • google the command to show hidden files
  • paste ‘defaults write com.apple.finder AppleShowAllFiles YES’
  • relaunch the finder

And once done with my job, i don’t want to keep seeing all the hidden system files everywhere so I need again:

  • fire up the terminal
  • google the command to hide hidden files
  • paste ‘defaults write com.apple.finder AppleShowAllFiles NO’
  • relaunch

Well all this makes me try and avoid the task whole together. Ideally it should be just one call to toggle the hidden mode state. I find the best way to to do this is have a workflow app. This app just checks and toggles the status of hidden files flag. As a bonus it relaunches the finder for you.

So in essence all you need to do is:

  • Hit command + space (to bring up spotlight)
  • type ‘sh’ or ‘sho’ or ‘show’ etc.
  • hit return

hidden_files

And when you are done, you just need to do the same again!

Here is a download link to this app/widget. 
(just make sure you put it in a location that spotlight can search, Applications folder will do nicely)

This is based on a apple script I  found on some online forum.

# check if hidden files are visible and store result in a variable
isVisible=”$(defaults read com.apple.finder AppleShowAllFiles)”

# toggle visibility based on variables value
if [ “$isVisible” = FALSE ]
then
defaults write com.apple.finder AppleShowAllFiles TRUE
else
defaults write com.apple.finder AppleShowAllFiles FALSE
fi

# force changes by restarting Finder
killall Finder

SWRevealViewController disabling user interaction when toggled to Rearview

There is currently no iOS system component that works like a reveal view. I am talking about that sort of left sliding drawer implementation you see in the Facebook app.

I use a third party library called SWRevealViewController. Its a great peice of code by a developer named John Lluch. However there is one annoying problem with the code and every designer I work with insists I have.

When we slide the drawer to reveal the rearview, the front view is partially visible on the right side. If the user taps on a UIControl item, like a UIButton, on this partially visible view, the action is performed while still in the partially visible state. This can be annoying and creates a undesired use case.

SWRevealViewControllerTapIssue

The way I tackle this is to show an overlay view on top of the partially visible front view. This overlay firstly acts as an indicator that this view is currently inactive. Secondly it captures any touch on this view to toggle the front view back!

SWRevealViewFix

Instead of having to write this implementation in every project, I have forked SWRevealViewController and handled it in that code instead. All I have to set now is a boolean called ‘shouldUseFrontViewOverlay’ to YES.

If you find this idea useful, go ahead and use my fork at GitHub.

YouTube API on iOS : Uploading a video

Update: If you are only targeting iOS 8, I have created a Framework bundle to make things simpler. 

As straightforward as it may seem, one can get lost trying to get their app to use the YouTube API. This tutorial will explain how to use the API to get a list of videos in a playlist and  then upload a video right from our app!

These are the basic steps we will be following:

0. Create a iOS project in Xcode.
1. Register an App with Google.
2. Get the YouTube Data API.
3. Integrate the API into your project.
4. Configure the API for your Google App.
5. Use the API to get Playlist data and upload a video.

A lot to cover, lets get started.

0. Create a iOS project in Xcode.
Obviously we will need a iOS project. So go ahead and create a new iOS project in Xcode. Note the bundle ID of the project from the plist file, we will need this later.

1. Register an App with Google.
We need to register an application with Google. This is needed so the API requests coming to YouTube from your App can be identified. It is pretty straightforward. Firstly, you will need a google account. Then head over to Google Developers Console.

1. Create project

Here you will see a projects tab with a ‘ CREATE PROJECT’ button, click it. This will present you with a window where you need to provide some project details. First is Project Name, self explanatory. Next is Project ID which is auto-generated but can be changed. However it needs to be unique globally! I suggest you use the one provided by default as its not visible to the end user anyway. Read and accept the Terms of Service to continue.

2. Project Details

If the information you provided was valid, you should be redirected to your Project’s page. Note that this may take some time while your project request is being approved. Click on the ‘APIs and Auth’ tab and then select ‘Credentials’. You should see a OAuth section with Client ID and Email Address. However these are not the credentials we are interested in. We need credentials for a native app. Click the ‘CREATE NEW CLIENT ID’ button.

3. Project Credentials

In the Create Client ID window, select ‘Installed application’, followed by ‘iOS’ for type. Next you will need to provide your Application’s Bundle ID, this is found in the .plist file of your project or in the Project settings window under General.

4. New Client ID

Hit Create button to register. You will get a new Client ID and Client secret, this is what we will need later.

5. New Client ID created

2. Get the YouTube Data API
At the time of writing this tutorial the latest version of Google Data API was ‘v3’. The first thing we will need to do is download the objective-C client library. We will check out the svn repository. Open up Terminal and move to the directory where you want to place this downloaded code. To check out the code use this command in Terminal:

svn checkout http://google-api-objectivec-client.googlecode.com/svn/trunk/ google-api-objectivec-client-read-only

*In case this does not work for some reason, you can get the latest url here.

This will create a ‘google-api-objectivec-client-read-only‘ directory at the location you chose.

3. Integrate the API into your project.

There are 3 ways to integrate the client library into your project: as a iOS static library, as a framework or directly by including source files. I have found the last option to be most convinent and thats what I will be using in this tutorial.

In case you want to use a different approach, this link will be helpful.

We will need to include a bunch of files into the project. Create a new group within the project, (mine is called ‘Google-API-Stuff’) to put all these files in.

3.1 Add the ‘GTLCommon_Sources.m’ and ‘GTLNetworking_Sources.m’ files to your project.
Open the downloaded client API folder we just checked out. Open the ‘Source’ folder. Here you should see these two files. Copy them into your project, under the new group we just created. Make sure you DO NOT select the ‘Copy items into destination group’s folder’ option.

6. Add 2 source files

3.2 Adding library’s source folders to Header Search Paths.
This one requires some work. What will do here is tell Xcode where to find the relevant files for the Google API from our machine instead of copying it into our project.

7. Add search paths

a) In Xcode navigator select your project file.
b) Make sure you have the project selected and not the target.
c) Click the ‘Build Settings’ tab.
d) In the search box, type ‘Header Search Paths’
e) You should now see the entry for ‘Header Search Paths’ below. Double click it to open the edit window.
f) You can click the little ‘+’ button at the bottom to add the paths required.
8. Add values to header search paths
g) We need to add the FULL paths for the following folders:

 Source
 Source/Objects
 Source/Utilities
 Source/HTTPFetcher
 Source/OAuth2
 Source/OAuth2/Touch

For example in my case the paths are:

 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source
 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/Objects
 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/Utilities
 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/HTTPFetcher
 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/OAuth2
 /Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/OAuth2/Touch

9. Added paths

h) Now that we have added the common files required for the API, we will need to repeat the above steps for the particular google service we wish to use, in our case YouTube :]

Open the downloaded client API folder again and navigate to Source/Services/YouTube/Generated.

From here copy the ‘GTLYouTube_Sources.m’ to your project group where we placed the previous copied files.

10. Add _sources file

Next we will need to add this path to the Header Search Paths like we did earlier. This time the folder we need is:

Source/Services/YouTube/Generated

In my case the full path is:

/Users/nirbhay/Documents/Development/Personal/Resources/google-api-objectivec-client-read-only/Source/Services/YouTube/Generated

3.3 Add OAuth 2 sign-in view.
YouTube services require OAuth to establish a secure connection with the client. We need to add this view to our project as well. In the client API folder, navigate to:
/Source/OAuth2/Touch

Here you will see GTMOAuth2ViewTouch.xib.
Copy it into your project as well.

11. Add OAuth controllers

3.4 Add required frameworks
We need to following frameworks linked to our project.
a) Security.framework
b) SystemConfiguration.framework

12. Adding Frameworks

3.5 ARC
In case you are using ARC, which you should, you will need to perform another step. The API files we are compiling do not use ARC while our project does. Therefore we will need to specifically tell Xcode to treat these files as ‘not using ARC’ .

Head over to the Build Phases of your target. Here under compile sources, you should see the three API .m files we added to our project along with other files from our project. We need to add a flag to these three files to mark them as non ARC. Double click a file, this will open a window, insert the following flag:
-fno-objc-arc
Do this for all the three files (GTLCommon_Sources.m, GTLNetworking_Sources.m, GTLYouTube_Sources.m).

13. Adding no ARC flag

This should do it! Our project is now ready to link with the API. Build project, there should be no errors.

4. Configure the API for your Google App.

Basically our App is now ready to talk to YouTube. All we have to do is authenticate and then call appropriate API functions to get/send data. To authenticate we will need the Client ID and Client Secret that we got earlier. After this, the user will need to log into her/his google account and provide permission to our app to use YouTube on their behalf.

Though this process is not very complicated it get a little confusing at first. I wrote a simple wrapper class when I was working with this API. Please use it for now to make things easier. Later you can modify it or write your own class for any particular requirement. Download the YouTubeHelper here. Add the YouTubeHelper.h and YouTubeHelper.m files to your project.

To work with YouTubeHelper, include the ‘YouTubeHelper.h’ file into your viewController. Your class will also need to conform to the YouTubeHelperDelegate protocol.

#import <UIKit/UIKit.h>
#import "YouTubeHelper.h"
@interface ViewController : UIViewController
@end

The protocol has some mandatory methods:

- (NSString *)youtubeAPIClientID;
Here you will provide your app’s Client ID that we got from the Google Developer Console earlier.

- (NSString *)youtubeAPIClientSecret;
Here you will provide the Client Secret.

- (void)showAuthenticationViewController:(UIViewController *)authView;
When the OAuth process starts, the API needs to present its view controller to the user. YouTubeHelper calls this delegate method and provides you with the viewController to be displayed. It is then your responsiblity to push/present this.

- (void)authenticationEndedWithError:(NSError *)error;
After authentication this delegate is called. If the error is nil, it means the authentication was successfull.

Ok done, now what? After implemeting the delegates, its time to start using the API.

Inside your class create an object of the YouTubeHelper class using the initWithDelegate: method. Now that you have an instance of this object, you can use it to authenticate, get uploaded videos playlist and upload a video.

1) Authenticate:

User will need to authenticate the application for the first use. After auth the information is stored in user’s keychain and can be reused on subsequent runs.

To authenticate, call the
- (void)authenticate;
method on YouTubeHelper object. This will be followed by the two delegate methods disscussed earlier being called.

In case the user wishes to sign out, call the
- (void)signOut;
method. This will delete the auth info stored in keychain.

2) Getting uploaded playlist:

If the authentication is done, we can now finally get some useful information from youtube. Call the
- (void)getUploadedPlaylist;
method. This will fetch the upload channel and a list of videos uploaded to it. After the data is fetched the
- (void)uploadedVideosPlaylist:(NSArray *)array;
delegate is called. This will return an array of ‘GTLYouTubePlaylistItem’ items. To test this you can print the names of the items using
item.snippet.title.


- (void)uploadedVideosPlaylist:(NSArray *)array;
{
NSLog(@"uploaded list:");
for (int ii = 0; ii < array.count; ii++) {
GTLYouTubePlaylistItem* item = array[ii];
NSLog(@" %@", item.snippet.title);
}
}

Make sure you have a video uploaded on youtube before testing this.

3) Uploading a video.

To upload a video, you will need to call the
- (void)uploadPrivateVideoWithTitle:(NSString *)title
description:(NSString *)description
commaSeperatedTags:(NSString *)tags
andPath:(NSString *)path;

method.

It accepts a title (mandatory), description (optional), tags (optional) and path (mandatory).

You can track the upload progress by implementing the
- (void)uploadProgressPercentage:(int)percentage;
method.

For additional help on using YouTubeHelper check out the demo project. However note that this project will not run on your machine until you set up all the links mentioned above.

Follow

Get every new post delivered to your Inbox.

Join 224 other followers