LoginSignup
35
37

More than 5 years have passed since last update.

ストレージの空き容量を確認する

Last updated at Posted at 2015-06-11

参考: iOS、Androidの空き容量をコードで調べる

Android

android.cs
public int AvailableStorageMB {
    get {
        var statFs = new AndroidJavaObject ("android.os.StatFs", Application.temporaryCachePath);
        var availableBlocks = statFs.Call<long> ("getAvailableBlocksLong");
        var blockSize = statFs.Call<long> ("getBlockSizeLong");
        var freeBytes = availableBlocks * blockSize;
        return freeBytes / MEGA_BYTES;
    }
}

iOS

※ Android 側で指摘のように int だと大きな値になると計算途中の値がオーバーフローする可能性があるので、大きな値を扱える型にする必要があるかもです。(コメント欄参照)

storage.mm
/*
 * ストレージ空き容量の取得
 */
int storageAvailableMb_() {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:nil];

    if (dict) {
        int Mb = 1024 * 1024;
        float free = [[dict objectForKey: NSFileSystemFreeSize] floatValue] / Mb;
        return (int)free;
    }

    return 0;
}
storage.cs
    [DllImport("__Internal")]
    private static extern int storageAvailableMb_();

    public static int storageAvailableMb {
        get {
            if (Application.platform == RuntimePlatform.IPhonePlayer) {
                return storageAvailableMb_();
            }
            throw new System.NotSupportedException ();
        }
    }
35
37
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
37