It is possible to know if a string is encoded in base64?

风格不统一 提交于 2019-12-04 19:22:46

There is no need to check in advance if the string contains valid Base-64. You just have to check the return value, which is nil when the input is not recognized as valid Base-64:

if let decodedData = NSData(base64EncodedString: someString, options: nil) {
    // ...
} else {
    println("Not Base64")
}

Update for Swift 4:

if let decodedData = Data(base64Encoded: someString) {
    // ...
} else {
    print("Not Base64")
}

You can use the regular expression to check a string match base64 encoding or not, like this:

^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$

In base64 encoding, the character set is [A-Z,a-z,0-9,and + /], if rest length is less than 4, fill of '=' character.

^([A-Za-z0-9+/]{4})* means the String start with 0 time or more base64 group.

([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==) means the String must end of 3 forms in [A-Za-z0-9+/]{4} or [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==

Basic Rule is:

  • Check that the length is a multiple of 4 characters
  • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters

Please Use For Base64 Validation

OtherWise Add The Pod in The Project pod 'SwiftValidators'

Example

if Validators.isBase64()("mnbzcxmnbnzzxmnb==")
{
print("Validate Yes")
}
else
{
print("Not Validate")
}

You can create a string extension to validate this and make use of guardor a simple if would also do

  extension String
  {
    func isStringBase64() -> Bool {
        guard Data(base64Encoded: self) != nil else {
            return false
        }
        return true
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!