i wrote code for dynamic video , that is to be stored in documents and use it any wher of that video in our program
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
ipc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];
ipc.delegate = self;
ipc.editing = NO;
[self presentModalViewController:ipc animated:YES];
The below code will help you,
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)imagePickerControl didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoURL;
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] ||
[type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
}
[self saveVideoToFileFromURL:videoURL];
[self dismissModalViewControllerAnimated:YES];
}
-(void)saveVideoToFileFromURL:(NSURL*)videoStorageURL
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDate *todayDateObj = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"ddMMyyyyHHmmss"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"movie%#.mov",[dateFormat stringFromDate:todayDateObj]] ];
[dateFormat release];
NSData *data = [NSData dataWithContentsOfURL:videoStorageURL];
[data writeToFile:filePath atomically:YES];
}
Following code method insert into AppDelegate.h file
#property (nonatomic , retain) MPMoviePlayerViewController *mPlayer;
-(void)initAndPlayMovie:(NSURL *)movieURL andViewController:(UIViewController*)vCtr;
Following code insert into AppDelegate .m file
pragma mark - Media player
-(void)initAndPlayMovie:(NSURL *)movieURL andViewController:(UIViewController*)vCtr
{
self.mPlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
// set source type streaming
[self.mPlayer.moviePlayer setMovieSourceType:MPMovieSourceTypeUnknown];
[self.mPlayer.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
// fit to screen mode
[self.mPlayer.moviePlayer setScalingMode:MPMovieScalingModeAspectFit];
// full screen mode
[self.mPlayer.moviePlayer setFullscreen:YES animated:YES];
[vCtr presentMoviePlayerViewControllerAnimated:self.mPlayer];
}
-(void)stopPlaying_dismissMoviePlayer
{
[self.mPlayer.moviePlayer stop];
[self.mPlayer dismissMoviePlayerViewControllerAnimated];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
[self stopPlaying_dismissMoviePlayer];
}
Following code insert into .h file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"
#interface locallyCacheMP3FileViewController : UIViewController
- (IBAction)playAudio:(UIButton*)sender;
#property (nonatomic, retain) ASIHTTPRequest *rqstForAudio;
#end
Synthesize the variable
#synthesize rqstForAudio=_rqstForAudio;
Create method name as playAudio which connect to the button press event.
#pragma mark - View lifecycle
- (IBAction)playAudio:(UIButton*)sender
{
NSString *strAudioURL=#"Your Video link";
// check first locally exists or not
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#/%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
AudioFolder];
NSDictionary *dOfAudios=[NSDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios valueForKey:strAudioURL]) {
[APP_DEL initAndPlayMovie:[NSURL fileURLWithPath:[dOfAudios valueForKey:strAudioURL]] andViewController:self];
} else {
NSURL *audioURL = [NSURL URLWithString:strAudioURL];
NSString *strPathToDownload=[NSString stringWithFormat:#"%#/%#",[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
[strAudioURL lastPathComponent]];
if(!self.rqstForAudio || [self.rqstForAudio isFinished]) {
self.rqstForAudio=[ASIHTTPRequest requestWithURL:audioURL];
[self.rqstForAudio setDelegate:self];
[self.rqstForAudio setAllowResumeForFileDownloads:YES];
[self.rqstForAudio setCachePolicy:ASIUseDefaultCachePolicy];
[self.rqstForAudio setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[self.rqstForAudio setDidFailSelector:#selector(failedToLoad:)];
[self.rqstForAudio setDidFinishSelector:#selector(finishedLoading:)];
[self.rqstForAudio setDownloadCache:[ASIDownloadCache sharedCache]];
[self.rqstForAudio setDownloadDestinationPath:strPathToDownload];
[self.rqstForAudio startAsynchronous];
}
}
}
You can download the Source code and tutorial here
Related
I have an HTML document with a link that runs JavaScript code:
<a href="http://www.tricedesigns.com/temp/drm.pdf" onclick="app.openExternalDoc();">Open pdf</button>
<script type="text/javascript" src="../assets/js/index.js"></script>
<script type="text/javascript" src="../assets/js/ExternalFileUtil.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script src="../cordova.js"></script>
The index.js All this works fine
As does the ExternalFileUtil.js.
Here is the CDVExternalFileUtil.h file:
#import <Cordova/CDV.h>
#interface CDVExternalFileUtil : CDVPlugin <UIDocumentInteractionControllerDelegate> {
NSString *localFile;
}
- (void) openWith:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) cleanupTempFile: (UIDocumentInteractionController *) controller;
#end
And here is the CDVExternalFileUtil.m file:
#import "CDVExternalFileUtil.h"
#implementation CDVExternalFileUtil
- (void) openWith:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
CDVPluginResult* pluginResult;
NSString* callbackID = [arguments pop];
[callbackID retain];
NSString *path = [arguments objectAtIndex:0];
[path retain];
NSString *uti = [arguments objectAtIndex:1];
[uti retain];
NSLog(#"path %#, uti:%#", path, uti);
NSArray *parts = [path componentsSeparatedByString:#"/"];
NSString *previewDocumentFileName = [parts lastObject];
NSLog(#"The file name is %#", previewDocumentFileName);
NSData *fileRemote = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:path]];
// Write file to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {NSLog(#"Documents directory not found!");}
localFile = [documentsDirectory stringByAppendingPathComponent:previewDocumentFileName];
[localFile retain];
[fileRemote writeToFile:localFile atomically:YES];
NSLog(#"Resource file '%#' has been written to the Documents directory from online", previewDocumentFileName);
The problem seems to be around this area (as it works on iPhone, but not iPad so I assume its something to do with the layout, Here is another similar question
// Get file again from Documents directory
NSURL *fileURL = [NSURL fileURLWithPath:localFile];
UIDocumentInteractionController *controller = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
controller.delegate = self;
controller.UTI = uti;
[controller retain];
CDVViewController* cont = (CDVViewController*)[ super viewController ];
CGRect rect = CGRectMake(0, 0, cont.view.bounds.size.width, cont.view.bounds.size.height);
[controller presentOptionsMenuFromRect:rect inView:cont.view animated:YES];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: #""];
[self writeJavascript: [pluginResult toSuccessCallbackString:callbackID]];
[callbackID release];
[path release];
[uti release];
}
- (void) documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
NSLog(#"documentInteractionControllerDidDismissOpenInMenu");
[self cleanupTempFile:controller];
}
- (void) documentInteractionController: (UIDocumentInteractionController *) controller didEndSendingToApplication: (NSString *) application {
NSLog(#"didEndSendingToApplication: %#", application);
[self cleanupTempFile:controller];
}
- (void) cleanupTempFile: (UIDocumentInteractionController *) controller
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL fileExists = [fileManager fileExistsAtPath:localFile];
NSLog(#"Path to file: %#", localFile);
NSLog(#"File exists: %d", fileExists);
NSLog(#"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:localFile]);
if (fileExists)
{
BOOL success = [fileManager removeItemAtPath:localFile error:&error];
if (!success) NSLog(#"Error: %#", [error localizedDescription]);
}
[localFile release];
[controller release];
}
#end
Sorry for the large amount of code, I have been stuck on this View/Download PDF for 5 days now, Any help would be great
I am creating an app which will record a video using UIImagePickerController and I am saving the recorded video in documents directory and trying to play back the video on click of USE (want to show the full first frame of recorded video along with play button in the middle like the native application of iPhone).
I am able to record the video and save it into document directory but unable to create the frame and playback.
I tried to move on new class where I can play the recorded video but gets crashed on click of USE button.
Here is my code
-(void)btnRecord_Press
{
BOOL canRecordVideo;
canRecordVideo = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
if (canRecordVideo)
{
UIImagePickerController *videoRecorder = [[UIImagePickerController alloc]init];
videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
videoRecorder.delegate=self;
videoRecorder.showsCameraControls = TRUE;
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF CONTAINS %#)",#"movie"]];
BOOL movieOuputPossible = (videoMediaTypesOnly!=nil);
if (movieOuputPossible)
{
videoRecorder.mediaTypes = videoMediaTypesOnly;
[self presentViewController:videoRecorder animated:YES completion:nil];
}
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
[self dismissViewControllerAnimated:NO completion:nil];
PlayMovie *play = [[PlayMovie alloc]initWithNibName:#"PlayMovie" bundle:Nil];
[self.navigationController pushViewController:play animated:YES];
}
Any help would be appreciable.
Thanks
I did this using this code.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
[self dismissViewControllerAnimated:NO completion:nil];
[self Play];
}
-(void)Play
{
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
player = [[MPMoviePlayerController alloc]initWithContentURL:videoURL];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(btnDone_Press) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
self._player.shouldAutoplay = NO;
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
screenSize = [[UIScreen mainScreen]bounds].size;
if (screenSize.height >480.0f)
{
player.view.frame = CGRectMake(0, 0, 320, 548);
}
else
{
player.view.frame = CGRectMake(0, 0, 320, 460);
}
}
[self.view addSubview:player.view];
self._player.scalingMode = MPMovieScalingModeAspectFit;
self._player.fullscreen = YES;
[self._player play];
}
I have training app i want that when user click recordVideo button camera should launch to record video, is there any way to do this in ipad app.I have done audio recording already i need to do video recording.
//for video..
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/Mediaplayer.h>
#import <CoreMedia/CoreMedia.h>
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
for saving into Document folder & it also save in photo Library
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
//for video
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"video url-%#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString * videoName = [NSString stringWithFormat:#"student_%d_%d.mp4",stud_id,imgVidID];
videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
NSLog(#"video path-%#",videoPath);
[videoData writeToFile:videoPath atomically:YES];
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}
Try this ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Hopefully, It'll help you.
Thanks.
Just try it :
-(void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
NSString *moviePath = [[info objectForKey: UIImagePickerControllerMediaURL] path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)){
UISaveVideoAtPathToSavedPhotosAlbum (moviePath,self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
-(void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
if (error) {
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video Saving Failed" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:1.0];
}
else{
NSURL *videoURl = [NSURL fileURLWithPath:videoPath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURl options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
self.strUploadVideoURL = videoPath;
[imgPhoto setImage:[[[UIImage alloc] initWithCGImage:imgRef] autorelease]];
intWhenPushView = 2;
btnShare.enabled = YES;
btnFacebookShare.enabled = YES;
CGImageRelease(imgRef);
[generate release];
[asset release];
}
}
im trying to make an app that has 4 ImageViews and I want to allow the user to change the background on the different ImageViews by pressing an UIButton below each ImageView. I have written a code for this from a tutorial showing to do this with just one ImageView. I just copied and pasted 4 times for each button and changed some variables. But when I run it only the first ImageView changes its picture even if I press UIButton for 2nd, 3rd or 4th ImageView. here the code:
#import "ViewController.h"
#interface ViewController ()
{
UIImagePickerController *imagePickerController;
UIImagePickerController *imagePickerController2;
UIImagePickerController *imagePickerController3;
UIImagePickerController *imagePickerController4;
}
#end
#implementation ViewController
#synthesize firstImageView, secondImageView, thirdImageView, fourthImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)firstChangeButton:(id)sender
{
imagePickerController = [[UIImagePickerController alloc]init];
[imagePickerController setDelegate:self];
[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (IBAction)secondChangeButton:(id)sender
{
imagePickerController2 = [[UIImagePickerController alloc]init];
[imagePickerController2 setDelegate:self];
[imagePickerController2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController2 animated:YES completion:nil];
}
- (IBAction)thirdChangeButton:(id)sender
{
imagePickerController3 = [[UIImagePickerController alloc]init];
[imagePickerController3 setDelegate:self];
[imagePickerController3 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController3 animated:YES completion:nil];
}
- (IBAction)fourthChangeButton:(id)sender
{
imagePickerController4 = [[UIImagePickerController alloc]init];
[imagePickerController4 setDelegate:self];
[imagePickerController4 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController4 animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image1 = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image1);
NSString *myGrabbedImage = #"myGrabbedImage.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory stringByAppendingPathComponent:myGrabbedImage];
[data writeToFile:fullPathToFile atomically:YES];
[[self firstImageView]setImage:image1];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController2:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info2
{
UIImage *image2 = [info2 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data2 = UIImagePNGRepresentation(image2);
NSString *myGrabbedImage2 = #"myGrabbedImage2.png";
NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory2 = [path2 objectAtIndex:0];
NSString *fullPathToFile2 = [documentDirectory2 stringByAppendingPathComponent:myGrabbedImage2];
[data2 writeToFile:fullPathToFile2 atomically:YES];
[[self secondImageView]setImage:image2];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController3:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info3
{
UIImage *image3 = [info3 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data3 = UIImagePNGRepresentation(image3);
NSString *myGrabbedImage3 = #"myGrabbedImage3.png";
NSArray *path3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory3 = [path3 objectAtIndex:0];
NSString *fullPathToFile3 = [documentDirectory3 stringByAppendingPathComponent:myGrabbedImage3];
[data3 writeToFile:fullPathToFile3 atomically:YES];
[[self thirdImageView]setImage:image3];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController4:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info4
{
UIImage *image4 = [info4 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data4 = UIImagePNGRepresentation(image4);
NSString *myGrabbedImage4 = #"myGrabbedImage4.png";
NSArray *path4 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory4 = [path4 objectAtIndex:0];
NSString *fullPathToFile4 = [documentDirectory4 stringByAppendingPathComponent:myGrabbedImage4];
[data4 writeToFile:fullPathToFile4 atomically:YES];
[[self fourthImageView]setImage:image4];
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
How should i apply it for all 4 ImageViews?
Thanks in advance!
The problem is that all image pickers will call the same delegate method:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
When you set the delegate for the image picker controller like so:
[imagePickerController setDelegate:self];
You basically tell the image picker controller that self will be able to respond to the image picker delegate methods.
As you can see in the UIImagePickerControlDelegate, there's no such thing as:
– imagePickerController2:didFinishPickingMediaWithInfo:
and so on.
As a start, I would suggest rewriting your delegate method like this:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image1 = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image1);
NSString *myGrabbedImage = #"myGrabbedImage.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory stringByAppendingPathComponent:myGrabbedImage];
[data writeToFile:fullPathToFile atomically:YES];
if (picker == imagePickerController) {
[[self firstImageView]setImage:image1];
} else if (picker == imagePickerController2) {
[[self secondImageView]setImage:image1];
} else if (picker == imagePickerController3) {
[[self thirdImageView]setImage:image1];
} else {
[[self fourthImageView]setImage:image1];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
This way, all image picker images will be handled by the same method, thus reducing the amount of code.
I have a class for saveing score:
#import "cocos2d.h"
#interface ScoreData : NSObject<NSCoding> {
NSString *playerName;
NSDate *playDate;
}
-(NSString* )description;
#property (nonatomic, retain) NSString *playerName;
#property (nonatomic, retain) NSDate *playDate;
#end
#import "GameData.h"
#implementation ScoreData
#synthesize playerName;
#synthesize playDate;
#define kPlayerNameKey #"PlayerName"
#define kPlayDateKey #"playDate"
-(id)init
{
if( (self = [super init]) ) {
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.playerName
forKey:kPlayerNameKey];
[encoder encodeObject:self.playDate
forKey:kPlayDateKey];
}
- (id)initWithCoder:(NSCoder *)decoder
{
ScoreData *highScoreData = [[ScoreData alloc] init];
highScoreData.playerName = [[decoder decodeObjectForKey:kPlayerNameKey] string];
highScoreData.playDate = [[decoder decodeObjectForKey:kPlayDateKey] date];
return highScoreData;
}
#end
And in my GameLayer I call to save score like this:
#interface GameLayer : CCLayer
{
ScoreData *scoreData;
}
-(void)gameOver
{
scoreData.playerName = #"test";
scoreData.playDate = [NSDate new];
[[GameDataManager sharedGameDataManager] updateLocalScore:scoreData];
}
And the code to save the data:
-(void)updateLocalHighScore:(ScoreData *)scoreData
{
[highScoreDataArray addObject:scoreData];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:self.highScoreDataArray
forKey:#"LocalHighScoreData"];
[self writeApplicationData:dic bwriteFileName:#"teste.plist"];
}
-(BOOL) writeApplicationData:(NSDictionary *)data
bwriteFileName:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSMutableArray *a = [[NSMutableArray alloc] init];
a = [data objectForKey:#"ScoreData"];
NSMutableData *_data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:_data];
[archiver encodeObject:data forKey:#"GameData"];
[archiver finishEncoding];
[_data writeToFile:appFile atomically:YES];
[archiver release];
[data release];
return YES;
}
And the data was saved correctly...
Then I tried to read the data from plist:
-(BOOL) readApplicationData:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
if (myData == nil) {
return NO;
}
NSKeyedUnarchiver *un = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
NSMutableDictionary *dic = [un decodeObjectForKey:#"GameData"];
self.highScoreDataArray = [dic objectForKey:#"ScoreData"];
[un finishDecoding];
[un release];
return YES;
}
But the app crashed here:
- (id)initWithCoder:(NSCoder *)decoder
{
ScoreData *highScoreData = [[ScoreData alloc] init];
highScoreData.playerName = [[decoder decodeObjectForKey:kPlayerNameKey] string];
return highScoreData;
}
Saying:
[4011:207] -[NSCFString string]: unrecognized selector sent to instance 0x544dd10
[4011:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString string]: unrecognized selector sent to instance 0x544dd10'
Can anybody help me out of here. Thanks^_^
Well, the error message says it all. You are calling a -string method on NSString and since such a method does not exist, your app crashes. Moreover, the -string and -date messages there are completely unnecessary. Just remove them.
There are more problems in your code: for example: you should generally not alloc a new object in -initWithCoder:. If you do, you have a memory leak. The method should look like this:
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self != nil) {
self.playerName = [decoder decodeObjectForKey:kPlayerNameKey];
self.playDate = [decoder decodeObjectForKey:kPlayDateKey];
}
return self;
}
I haven't checked the rest of your code so it's very possible there are more bugs in it.