1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift・Objective-C】Base64のエンコード・デコード

Posted at

Base64とは?

base64とは、64進数を意味する言葉で、すべてのデータをアルファベット(a~z, A~z)と数字(0~9)、一部の記号(+,/)の64文字で表すエンコード方式です
ただ、データ長を揃えるためにパディングとして末尾に記号の=を使用するので、厳密にはbase64は、65文字の英数字から表現されます

エンコード

Swift

let testString = "Hello, playground"

let testData = testString.data(using: .utf8)

let encodedString = testData?.base64EncodedString()

print(encodedString!)    // SGVsbG8sIHBsYXlncm91bmQ=

Objective-C

NSString *testString = @"Hello, playground";

NSData *testData = [testString dataUsingEncoding:NSUTF8StringEncoding];

NSString *encodedString = [testData base64EncodedStringWithOptions:0];

NSLog(@"Encoded: %@", base64Encoded);

デコード

Swift

let restoreData = Data(base64Encoded: encodedString!)

let restoreString = String(data: restoreData!, encoding: .utf8)

print(restoreString!)    // "Hello, playground"

Objective-C

NSData *restoreData = [[NSData alloc]initWithBase64EncodedString:encodedString options:0];

NSString *restoreString = [[NSString alloc] initWithData:restoreData encoding:NSUTF8StringEncoding];

NSLog(@"Decoded: %@", restoreString);

参考

1
3
0

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?