2013年6月21日金曜日

バックグラウンドで動かす


AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    UIBackgroundTaskIdentifier bgTask;
}

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
    }];
}

以上でアプリがバックグランドに回っても動作し続けるが、10分までという制限がある。

しかし音声を再生したり、GPSを使っている場合は、イベントによって再度動かせる。

例えばGPSを使ってロケーションを取得していれば、ロケーションが変わったときに
ふたたび動き出す。

GPSをバックグランドで使うには、info.plistの編集が必要。

Information Property List の右の+をクリックして、Required background modesを選び、
item0のValueで、App registers for location updates を選ぶ。


2013年5月17日金曜日

FMDBによるデータベース検索


FMDBによるデータベース検索

NSURL *dirPath;
FMDatabase *db;
NSURL *dbPath;



    //Open DB
    dbPath = [dirPath URLByAppendingPathComponent:@"cdb.db"];
    db = [FMDatabase databaseWithPath:[dbPath absoluteString]];
    [db open];

    //Read all
    FMResultSet *rs = [db executeQuery:@"select * from cdb"];
                    
    while ([rs next]){
       ContId[j] = [rs stringForColumn:@"ContId"];
       CateId[j] = [rs stringForColumn:@"CateId"];
       title[j]  = [rs stringForColumn:@"Title"];
       imageFile[j] = [rs stringForColumn:@"ImageFile"];
       detail1[j] = [rs stringForColumn:@"Detail1"];
                        
       j++;
    }
    [rs close];
    [db close];


特定の項目検索の場合

    FMResultSet *rs = [db executeQuery:@"select * from cdb where CateId = ?", cid];



特定のワードを含む検索の場合
   //検索ワード
    NSString *srchtxt = [[NSString alloc]init] ;
    srchtxt = [srchtxt stringByAppendingString:@"%%"];
    srchtxt = [srchtxt stringByAppendingString:srchtext.text];
    srchtxt = [srchtxt stringByAppendingString:@"%%"];
    FMResultSet *rs = [db executeQuery:@"select * from cdb where Title like ?", srchtxt];


データベースの作成
    //Create DB
    dbPath = [dirPath URLByAppendingPathComponent:@"cdb.db"];
    db = [FMDatabase databaseWithPath:[dbPath absoluteString]];
    [db open];
    [db beginTransaction];

    [db executeUpdate:@"delete from cdb"];
    [db executeUpdate:@"create table cdb (ContId text, CateId text, Title text, ImageFile text, Detail1 text)"];
    [db commit];

データベース書き込み
    //Insert DB
    [db beginTransaction];
    [db executeUpdate:@"insert into cdb (ContId,CateId,Title,ImageFile,Detail1) values (?,?,?,?,?)",ContId,CateId,Title,ImageFile,Detail1];
     [db commit];




2013年4月25日木曜日

PopUp Viewのサイズ指定


PopUp Viewの大きさは、UIViewのほうに記述する。
PopUp Viewに記述しても効かない。

    if (setPop != nil)
    {
        [setPop dismissPopoverAnimated:YES];
    }
    UIViewController *vc = [[UIViewController alloc] init] ;
    vc.view.frame = CGRectMake(0, 0, 300, 500);
    vc.contentSizeForViewInPopover = vc.view.frame.size;
    
    setPop = [[UIPopoverController alloc] initWithContentViewController:vc];
    [setPop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];

Print Menu表示(HTMLテキスト)


HTMLテキストを印刷する

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = @"document"; //self.documentName;
    pic.printInfo = printInfo;
    UIMarkupTextPrintFormatter *htmlFormatter = [[UIMarkupTextPrintFormatter alloc]initWithMarkupText:@"<html><body>samaple HTML</body></html>"]; //self.htmlString];
    htmlFormatter.startPage = 0;
    htmlFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1インチの余白
    pic.printFormatter = htmlFormatter;
    pic.showsPageRange = YES;
    
    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
        if (!completed && error) {
            NSLog(@"Printing could not complete because of error: %@", error);
        }
    };
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
        
    } else {
        [pic presentAnimated:YES completionHandler:completionHandler];
    }

 アプリケーションメニューの表示

外部アプリケーションのメニュ=を表示し、ファイルをアプリに送る


UIDocumentInteractionControllerは、iOS4から使えるが、facebook,twitter,Printなどは出てこない。
iOS6なら、UIActivityViewControllerを使う方よい。

ここでは、UIDocumentInteractionControllerのサンプルを載せる。




UIDocumentInteractionController *docInterCon;



    //データへのURL
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *dataFilePath = [bundle pathForResource:@"file" ofType:@".text"];
    NSURL *url = [NSURL fileURLWithPath:dataFilePath];
    
    //
    self.docInterCon = [UIDocumentInteractionController interactionControllerWithURL:url];
    self.docInterCon.delegate = self;
        
    //アプリケーションのメニューを表示
    BOOL isValid;
    isValid = [self.docInterCon presentOptionsMenuFromBarButtonItem:_barbtn animated:YES];
    if (!isValid){
        NSLog(@"アプリケーションがありません");
    }

2013年4月18日木曜日

ローカルにファイル保存


    //Get Directory path
    NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSURL *dirPath = nil;
    
    NSArray *appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
    
    if ([appSupportDir count ] >0)
    {
        dirPath= [[appSupportDir objectAtIndex:0]URLByAppendingPathComponent:bundleID];
        NSError *theErr = nil;
        if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theErr])
        {
            //error process
        }
    }
    
    //Write
    dirPath = [dirPath URLByAppendingPathComponent:@"aaa.txt"];
    
    BOOL result = [str writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
    
    if (result) NSLog(@"Success write");
    
    //Read
    NSString *str1 = [NSString stringWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&err];
    
    NSLog(@"Read: %@",str1);

画像ファイルとテキストファイルをダウンロードして保存

ネットワーク経由で画像ファイルとテキストファイルをダウンロードして保存する


NSString *urlstring;
NSURL *url;
NSError *err = nil;
NSURL *path;

//serverIp1 サーバーのURL (http://xxxx.jp/xxxx/)
//dirPath  保存先のURL
//imageFile 画像ファイル名
//textFile テキストファイル名

//Download ImageFile
urlstring = [serverIp1 stringByAppendingString:imageFile];

url = [NSURL URLWithString:urlstring];

NSData *data = [NSData dataWithContentsOfURL:url options:nil error:&err];

//Write
path = [dirPath URLByAppendingPathComponent:ImageFile];

BOOL result = [data writeToURL:path options:NSDataWritingAtomic error:&err];
if (result == NO) break;

//Download Text file
urlstring = [serverIp1 stringByAppendingString:textFile];

url = [NSURL URLWithString:urlstring];

NSString *str = [NSString stringWithContentsOfURL:url encoding:NSShiftJISStringEncoding error:&err];

//Write
path = [dirPath URLByAppendingPathComponent:textFile];

result = [str writeToURL:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (result == NO) break;