我正在编写一个从照片库中获取图像的类。我想要一种从库中返回选定图像的方法。所以我开始编写一个名为 MediaBrowser 的类。我使用了将给出选定图像的块。但我很困惑在哪里写块定义。如果我出错了,请更正代码。
在 MediaBrowser.h 中
@interface MediaBrowser : NSObject
typedef UIImage* (^MediaBrowserCompletionHandler)(void);
+ (id)sharedInstance;
- (BOOL)startMediaBrowserFromViewController:(UIViewController*)controller
completionHandler:(MediaBrowserCompletionHandler)completion;
@end
在 MediaBrowser.m 中
@interface MediaBrowser () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) MediaBrowserCompletionHandler completionHandler;
@end
@implementation MediaBrowser
static MediaBrowser *sharedMediaBrowser = nil;
+ (id)sharedInstance
{
if (nil != sharedMediaBrowser) {
return sharedMediaBrowser;
}
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMediaBrowser = [[MediaBrowser alloc] init];
});
return sharedMediaBrowser;
}
- (BOOL)startMediaBrowserFromViewController:(UIViewController *)controller completionHandler:(MediaBrowserCompletionHandler)completion
{
self.completionHandler = [completion copy];
if (([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
|| (controller == nil))
return NO;
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// Displays saved pictures from the Camera Roll album.
mediaUI.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
mediaUI.allowsEditing = NO;
mediaUI.delegate = self;
[controller presentModalViewController:mediaUI animated:YES];
return YES;
}
// UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *imageToUse;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
imageToUse = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
// Do something with imageToUse
if (self.completionHandler) {
// Pass here UIImage
self.completionHandler();
}
}
[picker dismissModalViewControllerAnimated:YES];
}
@end