iPhoneのサンプルプログラム

SATCHを用いたナビアプリ(1)の参考アプリ5

AppDelegate.h
#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate> {
    NSArray *NaviData;
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@property (retain, nonatomic) NSArray *NaviData;

@end

AppDelegate.m
#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize NaviData;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (retain, nonatomic) IBOutlet UITextView *txtMsg;

@end

ViewController.m
#import "ViewController.h"
#import "URLLoader.h"
#import "NaviXMLParser.h"
#import "AppDelegate.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize txtMsg;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self loadNaviData];
}

- (void)viewDidUnload
{
    [self setTxtMsg:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)loadNaviData
{
//  NSString *url = [NSString stringWithFormat:@"http://www.tosiyama.jp/university/iphone/navi0.xml"];
    NSString *url = [NSString 
                     stringWithFormat:@"http://www.tosiyama.jp/personal/cgi/navitest4.cgi"];

    URLLoader *loader = [[[URLLoader alloc] init] autorelease];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(loadNaviDataDidEnd:) 
        name:@"connectionDidFinishNotification"
        object:loader];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(loadNaviDataFailed:) 
        name:@"connectionDidFailWithError" 
        object:loader];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [loader loadFromUrl:url method:@"GET"];
}

- (void)loadNaviDataDidEnd:(NSNotification *)notification
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    URLLoader *loader = (URLLoader *)[notification object];
    NSData *xmlData = loader.data;
/*    
    NaviXMLParser *parser = [[[NaviXMLParser alloc] init] autorelease];
    
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    delegate.NaviData = [parser parseNaviData:xmlData];

    int num = (int)[delegate.NaviData count];
    int i;
    NSMutableString *s1 = [NSMutableString string];
    for (i = 0; i < num; i++)
    {
        NSString *s0 = [NSString stringWithFormat:@"[%d] %@(%@),",
                            (i+1), 
                        [[delegate.NaviData objectAtIndex:i] objectForKey:@"msg"],
                        [[delegate.NaviData objectAtIndex:i] objectForKey:@"command"]
                        ];
        [s1 appendString:s0];
    }
    
    txtMsg.text = s1;
*/
    txtMsg.text = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
}

- (void)loadNaviDataFailed:(NSNotification *)notification
{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"エラー" 
                          message:@"xmlデータの取得に失敗しました!" 
                          delegate:self 
                          cancelButtonTitle:@"閉じる" 
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (void)dealloc {
    [txtMsg release];
    [super dealloc];
}
@end

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

@interface URLLoader : NSObject {
    NSURLConnection *connection;
    NSMutableData *data;
}

@property (retain, nonatomic) NSURLConnection *connection;
@property (retain, nonatomic) NSMutableData *data;

- (void)loadFromUrl:(NSString *)_url method:(NSString *)_method;

@end

URLLoader.m
#import "URLLoader.h"

@implementation URLLoader

@synthesize connection;
@synthesize data;

- (void)connection:(NSURLConnection *)conn
        didReceiveResponse:(NSURLResponse *)response {
    self.data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)conn
        didReceiveData:(NSData *)receiveData {
    [self.data appendData:receiveData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"connectionDidFinishNotification"
        object:self];
}

- (void)connection:(NSURLConnection *)conn
        didFailWithError:(NSError *)error {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"connectionDidFailWithError"
     object:self];
}

- (void)loadFromUrl:(NSString *)_url method:(NSString *)_method {
    NSMutableURLRequest *req = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:_url]];
    [req setHTTPMethod:_method];
    self.connection = [NSURLConnection connectionWithRequest:req delegate:self];
}

- (void)dealloc {
    [connection release];
    [data release];
    [super dealloc];
}

@end

NaviXMLParser.h
#import <UIKit/UIKit.h>

@interface NaviXMLParser : NSObject <NSXMLParserDelegate> {
    NSMutableString *currentXpath;
    NSMutableArray *NaviData;
    NSMutableDictionary *currentNavi;
    NSMutableString *textNodeCharacters;
}

@property (retain , nonatomic) NSMutableString *currentXpath;
@property (retain , nonatomic) NSMutableArray *NaviData;
@property (retain , nonatomic) NSMutableDictionary *currentNavi;
@property (retain , nonatomic) NSMutableString *textNodeCharacters;

- (NSArray *) parseNaviData: (NSData *) xmlData;

@end

NaviXMLParser.m
#import "NaviXMLParser.h"

@implementation NaviXMLParser

@synthesize currentXpath;
@synthesize NaviData;
@synthesize currentNavi;
@synthesize textNodeCharacters;

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    self.currentXpath = [[[NSMutableString alloc] init] autorelease];
    self.NaviData = [[[NSMutableArray alloc] init] autorelease];
}

- (void)parser:(NSXMLParser *)parser 
    didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI 
    qualifiedName:(NSString *)qName 
    attributes:(NSDictionary *)attributeDict 
{
    [self.currentXpath appendString: elementName];
    [self.currentXpath appendString: @"/"];
    
    self.textNodeCharacters = [[[NSMutableString alloc] init] autorelease];
    
    if ([self.currentXpath isEqualToString: @"navi/guide/"]) {
        self.currentNavi = [[[NSMutableDictionary alloc] init] autorelease];
    }
}

- (void)parser:(NSXMLParser *)parser 
    didEndElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI 
    qualifiedName:(NSString *)qName 
{    
    NSString *textData = [self.textNodeCharacters stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([self.currentXpath isEqualToString: @"navi/guide/"]) 
    {
        [self.NaviData addObject:self.currentNavi];
        self.currentNavi = nil;
    } 
    else if ([self.currentXpath isEqualToString: @"navi/guide/command/"]) 
    {
        [self.currentNavi setValue:textData forKey:@"command"];
    } 
    else if ([self.currentXpath isEqualToString: @"navi/guide/msg/"]) 
    {
        [self.currentNavi setValue:textData forKey:@"msg"];
    }
    
    int delLength = [elementName length] + 1;
    int delIndex = [self.currentXpath length] - delLength;
    
    [self.currentXpath deleteCharactersInRange:NSMakeRange(delIndex,delLength)];
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{
    [self.textNodeCharacters appendString:string];
}

- (NSArray *)parseNaviData:(NSData *)xmlData 
{
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
    [parser setDelegate:self];
    [parser parse];
    
    return self.NaviData;
}

- (void) dealloc 
{
    [currentXpath release];
    [NaviData release];
    [currentNavi release];
    [textNodeCharacters release];
    [super dealloc];
}

@end

navitest4.cgi
#!/usr/local/bin/perl

use CGI qw(:standard);
use XML::Writer;
use Encode;

my $output = '';
my $writer = XML::Writer->new(
    OUTPUT      => \$output,
    DATA_MODE   => 1,
    DATA_INDENT => 1
);

$writer->xmlDecl('UTF-8');
$writer->startTag('navi');

my $str1 = "右に曲がってください!";

$writer->startTag('msg');
$writer->characters($str1);
$writer->endTag('msg');

$writer->endTag('navi');
$writer->end();

my $string = decode( 'shiftjis', $output );
print header('text/xml'), encode( 'utf8', $string );