Search code examples
c#xamarin.formsnsobjectformatexception

system.FormatException: 'Input string was not in a correct format.' in IAppversion class. Conversion from NSObject to string


I am trying to get the build version of my iOS project using IAppVersion class. But, I am getting Exception as system.formatException while deploying to the iOS simulator through remote login to the macbook. The error is "system.FormatException: 'Input string was not in a correct format.'" Actually its my first time to deploy iOS project into simulator through remote login. I tried so many methods to resolve the issue. But, none of them are working. Please let me know is there any method to convert NSObject to string and then to Int. Thank you.

 public class Version_iOS: IAppVersion
    {
        public string GetVersion()
        {
            return NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleShortVersionString").ToString();
        }
        public int GetBuild()
        {
            return int.Parse(NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion").ToString());

            /*NSObject k = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion");
            string z = k.Description;
            return int.TryParse(z);*/
        }
    }

I tried code which is commented also. Please refer the image [1]: https://i.sstatic.net/FjJwl.png


Solution

  • According to the CFBundleVesion documentation, "This key is a machine-readable string composed of one to three period-separated integers, such as 10.14.1."

    This means that it most likely won't be able to be parsed to an int. So instead of trying to parse it to an int, you could try parsing it to a Version:

    public Version GetBuild()
    {
        return Version.Parse(NSBundle.MainBundle.ObjectForInfoDictionary(
            "CFBundleVersion").ToString());
    }
    

    However, it sounds like it could return a single digit, which isn't valid for the Version class, so the safest bet is to just leave it as a string:

    public string GetBuild()
    {
        return NSBundle.MainBundle.ObjectForInfoDictionary(
            "CFBundleVersion").ToString();
    }
    

    One final thought: if you really want to return an int (the first number in the version), you could do something like:

    public int GetBuild()
    {
        return int.Parse(NSBundle.MainBundle.ObjectForInfoDictionary(
            "CFBundleVersion").ToString()
            .Split('.')[0]);
    }