#import "ViewController.h"
#import "GTMBase64.h"
@interface ViewController (){
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark -GTMBas4 64编码
- (IBAction)codeclick:(id)sender {
[self codeImg];
}
- (IBAction)encodeClick:(id)sender {
[self DecodeImg];
}
#pragma mark -文字编码
-(void)TextCode{
NSString *str=@"Hello world";
NSData *Data=[str dataUsingEncoding:NSUTF8StringEncoding];
//进行编码
Data =[GTMBase64 encodeData:Data];
NSString *codestr=[[[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding] autorelease];
self.lbMessage.text=codestr;
}
#pragma mark -图片编码
-(void)codeImg{
NSString *path=[[NSBundle mainBundle] pathForResource:@"school_back" ofType:@"png"];
UIImage *img= [UIImage imageWithContentsOfFile:path];
NSData *data=UIImageJPEGRepresentation(img, 1.0);//UIImageJPEGRepresentation返回图片较小,但是清晰度模糊
// NSData *data=UIImagePNGRepresentation(img);//UIImagePNGRepresentation图片大,清晰
data= [GTMBase64 encodeData:data];
NSLog(@"-->%@",[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
self.lbMessage.text=[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
//==========================
#pragma mark -文字解码
-(void)TextDecode{
NSString *codeStr=self.lbMessage.text;
NSData *data=[codeStr dataUsingEncoding:NSUTF8StringEncoding];
data= [GTMBase64 decodeData:data];
self.lbMessage.text=[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
#pragma mark -图片解码
-(void)DecodeImg{
NSString *codestr=self.lbMessage.text;
NSData *data=[codestr dataUsingEncoding:NSUTF8StringEncoding];
data=[GTMBase64 decodeData:data];
UIImage *ima=[UIImage imageWithData:data];
self.img.image=ima;
}
- (void)dealloc {
[_lbMessage release];
[_img release];
[super dealloc];
}
@end
添加一个实际应用的例子:
这是我在做项目的时候的一个登陆功能,用到了
Base base64_encode编码,数据解析我用的自带的解析方式:
-(void)loginBtnClicked{
if (_nameText.text.length==0) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"请输入手机号或用户名" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
} else if ([_passwordText.text isEqual:@""]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"请输入密码" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
} else {
NSString *str1 = _nameText.text;
NSString *str2 = _passwordText.text;
NSString *originStr = [NSString stringWithFormat:@"%@:%@",str1,str2];
NSData* originData = [originStr dataUsingEncoding:NSUTF8StringEncoding];
_encodeResult=[NSString stringWithFormat:@"%@ %@",@"Base",[originData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
NSURL *url=[NSURL URLWithString:@"http://api.pcitcsh.com/member?client=1&version=3.0"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod=@"POST";
//请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:_encodeResult forHTTPHeaderField:@"Authorization"];
//请求体
NSDictionary *json=@{
@"action":@"login"
};
NSData *data=[NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody=data;
//判断网络连接
if ([self isConnectionAvailable]) {
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//解析回调数据
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *strError=dict[@"message"];
NSString *strPhone = @"";
if (dict[@"data"] != nil) {
NSDictionary *dic = dict[@"data"];
if (dic.count > 0) {
if ([[dic allKeys] containsObject:@"mobile"]) {//如果字典中存在“mobile”这个字段就把他取出来
strPhone = [dic valueForKey:@"mobile"];
}
}
}
if ([strError isEqualToString:@"操作成功"])
{
//存储登陆名和密码以及手机号码
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
[userdefault setObject:_nameText.text forKey:@"username"];
[userdefault setObject:_passwordText.text forKey:@"password"];
[userdefault setObject:strPhone forKey:@"mobile"];
//同步
[userdefault synchronize];
WelcomeController *welcomeView = [[WelcomeController alloc]init];
[self.navigationController pushViewController:welcomeView animated:YES];
}
else
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户名或密码错误!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}else{
//提示网络连接
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查网络连接!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
}
}