How to Base64 encoding on the iPhone

前端 未结 9 2073
情话喂你
情话喂你 2020-11-29 03:13

How do I do Base64 encoding on the iPhone?

I have found a few examples that looked promising, but could never get any of them to work on the phone.

相关标签:
9条回答
  • 2020-11-29 04:11

    Seems as of iOS 7 you no longer need any libraries to encode in Base64. Following methods on NSData can be used to Base64 encode:

    • base64EncodedDataWithOptions: – base64EncodedStringWithOptions:
    0 讨论(0)
  • 2020-11-29 04:12

    You can see an example here.

    This is for iOS7+.

    I copy the code here, just in case:

    // Create NSData object
    NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
      dataUsingEncoding:NSUTF8StringEncoding];
    
    // Get NSString from NSData object in Base64
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
    // Print the Base64 encoded string
    NSLog(@"Encoded: %@", base64Encoded);
    
    // Let's go the other way...
    
    // NSData from the Base64 encoded str
    NSData *nsdataFromBase64String = [[NSData alloc]
      initWithBase64EncodedString:base64Encoded options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc] 
      initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    NSLog(@"Decoded: %@", base64Decoded);
    
    0 讨论(0)
  • 2020-11-29 04:12

    Download following two files from GitHub

    Base64.h
    Base64.m
    

    Add these files to your project

    Import header file in desired file

    #import "Base64.h"
    

    And use as to encode

    NSString *plainText = @"Your String";
    
    NSString *base64String = [plainText base64EncodedStringWithWrapWidth:0];
    

    Also you can decode it as

    NSString *plainText = [base64String base64DecodedString];
    
    0 讨论(0)
提交回复
热议问题