iPhoneSDK开发136技系列:第22技 使用粘贴板
大家知道UIKit的控件默认支持文本的拷贝和粘贴。当然你也可以在应用中使用这种功能来拷贝和粘贴其他东西:图像、SQLite数据库、文本或则任何文件。如果提供给用户的是一个具有集成功能的应用套件,这就将会是一种在不同应用之间共享数据的很好方式。
iPhone有两个系统粘贴板:一个是系统范围的用于拷贝粘贴操作的通用粘贴板(General Pasteboard),一个保持最近搜索字符串的查找粘贴板(Find Pasteboard)。此外,各个应用还可以创建它们各自的粘贴板以供其他应用使用。比如POS应用和信用卡终端应用之间就可以通过一个共享的粘贴板来传递支付明细。
每个添加到粘贴板的条目都有一个类型。更确切地说,如果一个条目被添加到粘贴板,它就有以一种或多种类型所进行的呈现。比如一个网页地址就可以存储为字符串或者URL。在粘贴板中存储多种呈现可以让条目的使用有更多的灵活性。比如一个电子邮件的客户端可以使用文本呈现以在消息正文中插入一个可读的URL字符串,而podcast应用则是需要NSURL的呈现来获取podcast。在该实例中由于拷贝图片到粘贴板的时候使用了PNG和JPEG两种呈现,进行粘贴的时候就可以根据类型进行查询和获取。而类型信息在MobileCoreServices框架中定义,所以使用的时候一定要记得添加这个库并添加相应的import声明。实例代码如下:
- #import <UIKit/UIKit.h>
- #import <MobileCoreServices/MobileCoreServices.h>
- @interface CopyPaste {
- }
- - (void)copyImage;
- - (void)pasteImageAsFile;
- @end
- @implementation CopyPaste
- - (void)copyImage {
- UIImage *p_w_picpath = [UIImage p_w_picpathNamed:@"p_w_picpath.png"];
- UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
- pasteBoard.persistent = YES;
- NSMutableDictionary *item =
- [NSMutableDictionary dictionaryWithCapacity:2];
- [item setValue:UIImagePNGRepresentation(p_w_picpath)
- forKey:(NSString*)kUTTypePNG];
- [item setValue:UIImageJPEGRepresentation(p_w_picpath,0.9)
- forKey:(NSString*)kUTTypeJPEG];
- [pasteBoard setItems: [NSArray arrayWithObject:item]];
- }
- - (void)pasteImageAsFile {
- UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
- if ( [pasteBoard containsPasteboardTypes:
- [NSArray arrayWithObject:(NSString*)kUTTypeJPEG]]) { //JPEG
- NSData *data = [pasteBoard dataForPasteboardType:
- (NSString*)kUTTypeJPEG];
- UIImage *p_w_picpath = [UIImage p_w_picpathWithData:data];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(
- NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *filePath = [[paths objectAtIndex:0]
- stringByAppendingPathComponent:@"paste.png"];
- NSLog(@"%@",filePath);
- [UIImageJPEGRepresentation (p_w_picpath)
- writeToFile:filePath atomically:YES];
- }else if ( [pasteBoard containsPasteboardTypes:
- [NSArray arrayWithObject:(NSString*)kUTTypePNG]]) { //PNG
- NSData *data = [pasteBoard dataForPasteboardType:
- (NSString*)kUTTypePNG];
- UIImage *p_w_picpath = [UIImage p_w_picpathWithData:data];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(
- NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *filePath = [[paths objectAtIndex:0]
- stringByAppendingPathComponent:@"paste.png"];
- NSLog(@"%@",filePath);
- [UIImagePNGRepresentation(p_w_picpath)
- writeToFile:filePath atomically:YES];
- }
- }
- @end