做一个简单的汉英/英汉词典,调用以下接口实现:
http://api.liqwei.com/translate/?language=zh-CN|en&content=汉字
http://api.liqwei.com/translate/?language=en|zh-CN&content=english
在Xcode中新建singleview工程,名为TinyDictionary.修改xib文件。
为textfield关联成员变量 _textField,为label关联成员变量 _lblResult 为按钮关联方法 pressFind.
//
// ViewController.h
// TinyDictionary
//
// Created by cloud on 13-3-26.
// Copyright (c) 2013年 cloud. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
IBOutlet UITextField *_textField;
IBOutlet UILabel *_lblResult;
}
- (IBAction)pressFind:(UIButton *)sender;
@end
原理介绍:textfield取得的值,调用网络接口进行转换,得到结果写到lable控件中去。
这里面牵涉到网络接口的访问,和编码转换。
常用字符集。
NSASCIIStringEncodeing=1
NSNEXTSTEPStringEncodeing=2
NSJapaneseEUCStringEncoding=3
NSUTF8StringEncoding=4
NSISOLatin1StringEncoding=5
NSSymbolStringEncoding =6
NSNonLossyASCIIStringEncoding=7
NSShiftJISStringEncoding=8
NSISOLatin2StringEncoding=9
NSUnicodeStringEncoding =10
NSWindowsCP1251StringEncoding =11
NSWindowsCP1252StringEncoding=12
NSWindowsCP1253StirngEncoding=13
NSWindowsCP1254StirngEncoding=14
NSWindowsCP1250StirngEncoding=15
NSISO2022JPStringEncoding=21
NSMacOSRomanStringEncoding=30
NSProprietaryStringEncoding=65536
GB2312字符集
NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
中文URL编码(encode)解码(decode)
NSString* s1=[@"http://www.163.com" stirngByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSStirng* s2=[string1 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
修改pressFind方法,我们来把英文翻译成中文
//
// ViewController.m
// TinyDictionary
//
// Created by cloud on 13-3-26.
// Copyright (c) 2013年 cloud. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_textField release];
[_lblResult release];
[super dealloc];
}
- (IBAction)pressFind:(UIButton *)sender {
if ([_textField.text length]==0) {
return;
}
//GB2312字符集
NSStringEncoding encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//编码中文url
NSString *strURL=[[NSString stringWithFormat:@"http://api.liqwei.com/translate/?language=en|zh-CN&content=%@",_textField.text] stringByAddingPercentEscapesUsingEncoding:encode];
NSURL* url=[NSURL URLWithString:strURL];
NSError *err=nil;
//以指定编码得到url给出的内容
NSString *strResult=[NSString stringWithContentsOfURL:url encoding:encode error:err];
if (err) {
NSLog(@"error=%@",[err description]);
}
else
{
_lblResult.text=strResult;
}
}
@end
运行,结果如下:
源码地址:http://download.csdn.net/detail/cloud95/5182217