在Phonegap中如何获得设备的可用空间

时间:2015-10-07 05:12:34

标签: cordova memory-management

我正在尝试在Android,ios和Windows平台上使用cordova制作离线在线应用程序。在这个应用程序中,有570MB数据存储在数据库中。所以我需要先检查设备的可用内存空间。但我总是得到0.我正在使用这段代码。给我任何解决方案,让我获得所有平台的免费空间。

cordova.exec(
    function(freeSpace) {
      console.log('reported free space is ' + freeSpace);
    },
    function() {
      console.log('failed');
    }, 
    "File", "getFreeDiskSpace", []
);

1 个答案:

答案 0 :(得分:1)

我为iOS提供了解决方案。 使用以下代码更新手机屏幕中的CDVFile.m:

- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command
{    
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {
        //NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);
        NSLog(@"Error Obtaining System Memory Info");
    }
    NSString* strFreeSpace = [NSString stringWithFormat:@"%llu", totalFreeSpace];
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace];

    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];

    //return totalFreeSpace;

}

然后在javascript文件中使用此代码。

cordova.exec(
    function(freeSpace) {
      console.log('reported free space is ' + freeSpace);
    },
    function() {
      console.log('failed');
    }, 
    "File", "getFreeDiskSpace", []
);