iPhoneのサンプルプログラム

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

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 *start_id = @"1103";
    NSString *target_id = @"1";    
    
    NSString *url = [NSString 
            stringWithFormat:@"http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=%@&target=%@",
                     start_id, target_id];

    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];

    NSArray *path1 = nil;
    NSArray *path2 = nil;
    
    int numPath = (int)[delegate.NaviData count];
    int i;
    NSMutableString *s1 = [NSMutableString string];
    
    switch (numPath) {
    case 1: [s1 appendString:@"フロア内の移動\n"];
            path1 = [delegate.NaviData objectAtIndex:0];
            break;
            
    case 2: [s1 appendString:@"フロア間の移動\n"];
            path1 = [delegate.NaviData objectAtIndex:0];
            path2 = [delegate.NaviData objectAtIndex:1];
            break;
    }
    
    int num = [path1 count];
    [s1 appendFormat:@"%d個の要素があります!\n", num];
    
    for (i = 0; i < num; i++)
    {
        NSString *msg = [[path1 objectAtIndex:i] objectForKey:@"msg"];
        int cmd = [[[path1 objectAtIndex:i] objectForKey:@"command"] intValue];
        
        if (msg == nil) {
            msg = @"なし";
        }
        NSString *s0 = [NSString stringWithFormat:@"[%d] %@(%d)\n", (i+1), msg, cmd];            
        [s1 appendString:s0];
    }
    
    if (numPath == 2) {
        num = [path2 count];
        [s1 appendFormat:@"%d個の要素があります!\n", num];
        
        for (i = 0; i < num; i++)
        {
            NSString *msg = [[path2 objectAtIndex:i] objectForKey:@"msg"];
            int cmd = [[[path2 objectAtIndex:i] objectForKey:@"command"] intValue];
            
            if (msg == nil) {
                msg = @"なし";
            }
            NSString *s0 = [NSString stringWithFormat:@"[%d] %@(%d)\n", (i+1), msg, cmd];            
            
            [s1 appendString:s0];
        }
    }
    
    txtMsg.text = s1;
}

- (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;
    NSMutableArray *PathData;
    NSMutableDictionary *currentGuide;
    NSMutableString *textNodeCharacters;
}

@property (retain , nonatomic) NSMutableString *currentXpath;
@property (retain , nonatomic) NSMutableArray *NaviData;
@property (retain , nonatomic) NSMutableArray *PathData;

@property (retain , nonatomic) NSMutableDictionary *currentGuide;
@property (retain , nonatomic) NSMutableString *textNodeCharacters;

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

@end

NaviXMLParser.m
#import "NaviXMLParser.h"

@implementation NaviXMLParser

@synthesize currentXpath;
@synthesize NaviData;
@synthesize PathData;
@synthesize currentGuide;
@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/path/"]) {
        self.PathData = [[[NSMutableArray alloc] init] autorelease];
    }
    else if ([self.currentXpath isEqualToString: @"navi/path/guide/"]) {
        self.currentGuide = [[[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/path/"]) 
    {
        [self.NaviData addObject:self.PathData];
        self.PathData = nil;
    }
    else if ([self.currentXpath isEqualToString: @"navi/path/guide/"]) 
    {
        [self.PathData addObject:self.currentGuide];
        self.currentGuide = nil;        
    }
    else if ([self.currentXpath isEqualToString: @"navi/path/guide/command/"]) 
    {
        [self.currentGuide setValue:textData forKey:@"command"];
    }
    else if ([self.currentXpath isEqualToString: @"navi/path/guide/msg/"]) 
    {
        [self.currentGuide 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];
    [PathData release];
    [currentGuide release];
    [textNodeCharacters release];
    [super dealloc];
}

@end

「http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=1103&target=1」の場合

「http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=1103&target=1104」の場合

「http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=1104&target=1103」の場合

「http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=2&target=1103」の場合

「http://www.tosiyama.jp/personal/cgi/navitest8.cgi?start=1&target=1103」の場合