Showing posts with label xcode. Show all posts
Showing posts with label xcode. Show all posts

Tuesday, October 24, 2017

Showing a Cocoa UI Alert Panel in pure C

You can display an AlertPanel even if you have a strictly command line app. In the example below it shows a NSPanel called from pure C.


    id app = NULL;

    id pool = (id)objc_getClass("NSAutoreleasePool");

    if (!pool)
    {
        return -1;
    }
    pool = objc_msgSend(pool, sel_registerName("alloc"));
    if (!pool)
    {
        return -1;
    }
    pool = objc_msgSend(pool, sel_registerName("init"));

    app = objc_msgSend((id)objc_getClass("NSApplication"),

                       sel_registerName("sharedApplication"));

    NSRunAlertPanel(CFSTR("Test"),

                    CFSTR("Your App is running!"),
                    CFSTR("Ok"), NULL, NULL);
    
    objc_msgSend(pool, sel_registerName("release"));

Sunday, December 22, 2013

Get file name and extension from URL path

How to get file name with extension in a URL path is relatively straight forward in iOS. 

The code below should work. Put your url into a NSURL variable named yourURL or whatever. Then type the below:

 NSString *JPEGfilename = [[yourURL absoluteString] lastPathComponent];

This will give you your JPEG filename or below:

 NSURL *yourURL = [NSURL urlWithString:@"http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg"];
 NSString *JPEGfilename = [yourURL lastPathComponent];

Friday, August 30, 2013

Downloading Content to Local iOS Documents Directory

This example shows you how to download a remote file into an iOS Documents Directory from your iOS device. This is helpful for updates, and persisting data into your application, to replace static data. This allows you to keep your data fresh and dynamic.

- (void) downloadNewContent {
    NSLog(@"Downloading New Content...");
    NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/temp"];
    NSError *error = nil;
    if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
    
    NSURL *url = [NSURL URLWithString:@"http://naep-sp2010dev.naepims.org:8889/update.zip"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    if(data) {
        stringPath = [stringPath stringByAppendingPathComponent:[url lastPathComponent]];
        [data writeToFile:stringPath atomically:YES];
    }
    

}

Purging Documents Directory in iOS

Your local sandboxed Documents directory may get stuffed with a bunch of garbage. To purge the directory and it's contents use this simple method:

- (void)purgeDocumentsDirectory
{
    NSLog(@"Purging Documents Directory...");
    NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
        [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
    }

}

Friday, May 10, 2013

Get substring from an NSString in Objective-C

In Objective-C / Cocoa to grab a substring from an NSString based on beginning and ending characters is easy. This is helpful if you want to parse HTML, JSON, or a REST statement returning. See below:


 NSString *sStr = [NSString stringWithFormat:@"%@", assetGroups[indexPath.row]];
 NSString *name= [[[[sStr componentsSeparatedByString:@"Beginning Char(s)"] objectAtIndex:1] componentsSeparatedByString:@"End Char(s)"] objectAtIndex:0]; 
 NSString *newString = [NSString stringWithFormat:@"%@", name];

Tuesday, March 12, 2013

Custom Transition(s) Using QuartzCore

UIStroryBoard when you push view controllers, or segues, it doesn't let you customize too much. What I ended up doing was override the perform method and used QuartzCore Animations to customize our transitions. I subclassed UIStoryBoardSegue and overwrote the perform function.

Below to customize for Push or Pop then for Segues. (For segues remember to change the class to the custom class in IB).

To do it from a normal pop or push (this does cross fade animation, adjust it for yours):


   #import <QuartzCore/QuartzCore.h>


 - (IBAction)launch1990:(id)sender {
    CATransition* transition = [CATransition animation];
    transition.duration = .45;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"1990Storyboard" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"1990"];
    [self.navigationController pushViewController:vc animated:NO];
  }
 

To do it from segue:

 
//ZHCustomSegue.h
#import <Foundation/Foundation.h>

@interface ZHCustomSegue : UIStoryboardSegue

@end


//  ZHCustomSegue.m
#import "ZHCustomSegue.h"
#import "QuartzCore/QuartzCore.h"

@implementation ZHCustomSegue


-(void)perform {

    UIViewController *sourceViewController = (UIViewController*)[self sourceViewController];
    UIViewController *destinationController = (UIViewController*)[self destinationViewController];

    CATransition* transition = [CATransition animation];
    transition.duration = .45;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade; //kCATransitionMoveIn; //, kCATransitionPush,   kCATransitionReveal, kCATransitionFade
   //transition.subtype = kCATransitionFromLeft; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom



    [sourceViewController.navigationController.view.layer addAnimation:transition
                                                            forKey:kCATransition];

    [sourceViewController.navigationController pushViewController:destinationController animated:NO];
}

Vibrate Handheld in Unity3D

This simple script tells the Game/App from Unity to shake/vibrate the Device if iOS/Android. If the device doesn't support vibrate, it'll simply do nothing!:

#if UNITY_IPHONE | UNITY_ANDROID

      Handheld.Vibrate();

#endif

Friday, January 25, 2013

Playing Music from iOS Music Playlist with Unity3D


With this simple coding you can play a playlist on your device from your Unity3D Game. Why license royalties when you can get the user to do it for you per individual basis.  I am using this in my game Snowboarding+ (see gameplay demo above). If there is no music on your device it'll finally play the local music in your Unity 3D app. This plays the playlist called Snowboarding+

in AppController.mm (also add MediaPlayer.framework):

#include <MediaPlayer/MediaPlayer.h>


- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
[self playMusic];
}


- (void) playMusic {
  // Instantiate a music player
    MPMusicPlayerController *appPlayer = [MPMusicPlayerController applicationMusicPlayer];
    
    // Shuffle all songs
    [appPlayer setShuffleMode:MPMusicShuffleModeSongs];
    
    // Assume we will not find our playlist
    BOOL playlistFound = NO;
    
    // Get a collection of all playlists on the device
    MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
    NSArray *playlists = [playlistsQuery collections];
    NSString *plus;
    plus = @"all";
    // Check each playlist to see if it is the right one
    for (MPMediaPlaylist *playlist in playlists) {
        NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
        if ([playlistName isEqualToString:@"Snowboarding+"]) {
            // Add the playlist to the player's queue and get out of here
            [appPlayer setQueueWithItemCollection:playlist];
            playlistFound = YES;
            plus = @"snowboarding+";
            break;
        }
    }
    
    // If no playlist found, just play All playlist
    if (!playlistFound) {
        for (MPMediaPlaylist *playlist in playlists) {
            NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
            if ([playlistName isEqualToString:@"All"]) {
                // Add the playlist to the player's queue and get out of here
                [appPlayer setQueueWithItemCollection:playlist];
                playlistFound = YES;
                plus = @"all";
                break;
            }
            else
            {
                //IF NO ALL play a random song
                [appPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
                plus = @"random";
            }
        }

    }
    
    // Start playing from the beginning of the queue
    [appPlayer play];
    
    if (appPlayer.playbackState == MPMusicPlaybackStatePlaying)
{                
UnitySendMessage("Camera", "isPlaying","TRUE");
NSLog(@"%@ is playing",plus);}
            else
{
                UnitySendMessage("Camera", "isPlaying","FALSE");
NSLog(@"internal music from Unity3D App is playing");}

}
}

In Unity 3D add the following to the Script on your Camera or any game object from above:

var isMusicPlaying: boolean = false;

@script RequireComponent(AudioSource)

function Start() {
    // Delay a clip by 10 sec (44100 samples)
  #if UNITY_EDITOR || UNITY_ANDROID || UNITY_OSX
      audio.Play(44100 * 5);     
   #endif

}

function isPlaying(message:String)
 {
  if (message == "TRUE") {isMusicPlaying = true; audio.Stop(); }
  if (message == "FALSE") {isMusicPlaying = false;  audio.Play();  }

  Debug.Log("Is the Music Playing from Device? " + message);
 }

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...