おけやの日々

株式会社おけやのブログです。業務、企画、技術の事など様々な事を書きます。

cocos2d-x で iOS の "do not backup" 属性を与える

吉田です。

前回の記事の技術的なお話です。

iOS は元々 Objective C++ という形で Objective-CC++ のコードを混在して書く事ができます。変態業ですね。これを使って "do not backup" を付けるコードを書きます

// NativeBridge.h
class NativeBridge
{
public:
    static void setDoNotBackup(const std::string& path);
};
// NativeBridge.mm
#import <Foundation/Foundation.h>
#include <string>
#include "NativeBridge.h"

void NativeBridge::setDoNotBackup(const std::string& path)
{
    NSError *err = nil;
    
    NSString *element = [NSString stringWithCString:path.c_str() encoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL fileURLWithPath:element];
    if( [url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&err] == NO)
    {
        NSLog(@"Error: Unable to exclude directory from backup: %@", err);
    }
}

こんな感じのコードを置いておいて以下のように使います。 まじょのおしごとでは zip のダウンロード、展開に AssetManager を使っていましてその例です。

    auto error = [](int errorCode){};
    auto progress = [](int status){};
    auto success = [](){};

    auto futils = FileUtils::getInstance();
    auto assetUrl = ASSET_URL_PREFIX + "/assets.zip";
    auto versionUrl = URL_PREFIX + "/v1/asset_version.json";
    auto assetDirPath = futils->getWritablePath();

#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
    assetDirPath = assetDirPath + "assets/";
    futils->createDirectory(assetDirPath);
    NativeBridge::setDoNotBackup(assetDirPath);
#endif

    auto assetManager = AssetsManager::create(assetUrl.c_str(), versionUrl.c_str(), assetDirPath.c_str(),
                                              error, progress, success);
    assetManager->retain();
    if(assetManager->checkUpdate()){
        assetManager->update();
    }