PDF opens on the iPhone, but not on the iPad - iphone

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

Related

Can't permanently save audio with AVAudioRecorder

An app i'm making has several views, each view has a record, stop and play button. The idea is that the user can record to a different sound file for each view.
I can record and playback a sound on each view but when i navigate away from the view and then navigate back the sound is gone.
I'm sorry to include so much code below but it's something i need to get to the bottom of.
Delegate.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>
#import <AVFoundation/AVFoundation.h>
#interface humptyDumptyAppDelegate : UIResponder <UIApplicationDelegate>
{
NSArray *dirPaths;
NSString *docsDir;
NSString *soundFilePathPage1;
NSString *soundFilePathPage2;
NSString *soundFilePathPage3;
NSString *soundFilePathPage4;
NSString *soundFilePathPage5;
NSString *soundFilePathPage6;
}
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) AVAudioRecorder *audioRecorder;
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
//example getter and setter functions
- (NSArray*) getDirPaths;
- (void) setDirPaths:(NSArray*)myDirPath;
- (NSString*) getDocsDir;
- (NSString*) soundFilePathForPageNumber:(int)pageNumber;
#end
Delegate.m
#import "humptyDumptyAppDelegate.h"
#implementation humptyDumptyAppDelegate
#synthesize window = _window;
#synthesize audioPlayer;
#synthesize audioRecorder;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
soundFilePathPage1 = [docsDir
stringByAppendingPathComponent:#"audiopage1.caf"];
soundFilePathPage2 = [docsDir
stringByAppendingPathComponent:#"page2.caf"];
soundFilePathPage3 = [docsDir
stringByAppendingPathComponent:#"page3.caf"];
soundFilePathPage4 = [docsDir
stringByAppendingPathComponent:#"page4.caf"];
soundFilePathPage5 = [docsDir
stringByAppendingPathComponent:#"page5.caf"];
soundFilePathPage6 = [docsDir
stringByAppendingPathComponent:#"page6.caf"];
return YES;
}
//getter function
- (NSArray*) getDirPaths{
return dirPaths;
}
//setter function
- (void) setDirPaths:(NSArray*)myDirPath{
dirPaths = myDirPath;
}
// get docs directory
-(NSString*) getDocsDir{
return docsDir;
}
// get sound file for page, passing the page number as an argument
-(NSString*) soundFilePathForPageNumber:(int)pageNumber{
switch (pageNumber) {
case 1:
return soundFilePathPage1;
break;
case 2:
return soundFilePathPage2;
break;
case 3:
return soundFilePathPage3;
break;
case 4:
return soundFilePathPage4;
break;
case 5:
return soundFilePathPage5;
break;
case 6:
return soundFilePathPage6;
break;
}
return nil;
}
page1.m
//this is called in viewDidLoad
-(void) prepareForAudioRecording
{
btnPlay.enabled = NO;
btnStop.enabled = NO;
int page = 1;
NSString *audioFilePath = [appDelegate soundFilePathForPageNumber:page];
NSURL *soundFileURL = [NSURL fileURLWithPath:audioFilePath];
NSError *error;
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
appDelegate.audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[appDelegate.audioRecorder prepareToRecord];
}
}
- (IBAction)recordAudio:(id)sender {
if (!appDelegate.audioRecorder.recording)
{
btnPlay.enabled = NO;
btnStop.enabled = YES;
[appDelegate.audioRecorder record];
}
}
- (IBAction)stopAudio:(id)sender {
btnStop.enabled = NO;
btnPlay.enabled = YES;
btnRecord.enabled = YES;
if (appDelegate.audioRecorder.recording)
{
[appDelegate.audioRecorder stop];
[self audioRecorderDidFinishRecording:appDelegate.audioRecorder successfully:YES];
} else if (appDelegate.audioPlayer.playing) {
[appDelegate.audioPlayer stop];
}
}
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
if (flag == YES){
NSLog(#"finished recording");
[appDelegate.audioPlayer.data writeToFile:[appDelegate soundFilePathForPageNumber:1] atomically:YES];
}
}
Like i said, i'm sorry for the amount of code included, but i'm unsure where the problem is. I'm calling the writeToFile method in the audioRecorderDidFinishRecording: method. I don't know if this is correct but i have a feeling that this is not the root of the problem.
Please help!!
this code saves to an audio file
what about copping the file to the documents directory
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#" sound.caf"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (!success){
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sound.caf"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:writableDBPath error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"file size: %lld",fileSize);
if (!success) {
NSLog(#"Failed to create writable database file with message: %#", [error localizedDescription]);
}
}
It turns out the problem was that in one of my pages i had my prepareForAudioRecording in viewDidAppear which was automatically overwriting the saved audio. Moving it to viewDidLoad did the trick

fetching document from iCloud giving me 3/4 content of that document not the full content

I'm new to iPhone Development.
I have integrated iCloud storage in my application. I am successful in uploading documents on iCloud.
My document's size is around 126799 bytes. During uploading on iCloud I have made sure that a proper document is uploaded on iCloud by printing its length and content on the console. But when I am fetching document from iCloud it only gives me 3/4 of the content of that document. I have also checked this on console by printing its length and content.
/////====== variables are declared in interface file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq)
{
NSLog(#"iCloud access at %#", ubiq);
// TODO: Load document...
[self loadDocument];
}
else
{
NSLog(#"No iCloud access");
}
}
- (void)loadDocument{
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
_query = query;
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSString *filename = #"supplimentlistdescription.txt";
NSPredicate *pred = [NSPredicate predicateWithFormat:#"%K like '%#'",filename,NSMetadataItemFSNameKey];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(queryDidFinishGathering:)
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
[query startQuery];
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
_query = nil;
[self loadData:query];
}
- (void)loadData:(NSMetadataQuery *)query {
if ([query resultCount] == 1)
{
NSMetadataItem *item = [query resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
Note *doc = [[Note alloc] initWithFileURL:url];
self.doc = doc;
[self.doc openWithCompletionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"iCloud document opened");
}
else
{
NSLog(#"failed opening document from iCloud");
}
}
];
}
else
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *fileurlstring = [NSString stringWithFormat:#"Documents/Federal Rules of Civil Procedure"];
NSLog(#"fileurlstring:%#",fileurlstring);
ubiquityURL = [[filemgr URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:fileurlstring];
[ubiquityURL retain];
NSLog(#"ubiquityURL1:%#",ubiquityURL);
if ([filemgr fileExistsAtPath:[ubiquityURL path]] == NO)
{
[ubiquityURL retain];
[filemgr createDirectoryAtURL:ubiquityURL withIntermediateDirectories:YES attributes:nil error:nil];
[ubiquityURL retain];
}
ubiquityURL = [ubiquityURL URLByAppendingPathComponent:#"supplimentlistdescription.txt"];
[ubiquityURL retain];
NSLog(#"ubiquityURL:%#",ubiquityURL);
Note *doc = [[Note alloc] initWithFileURL:ubiquityURL];
self.doc = doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success)
{
if (success) {
[doc openWithCompletionHandler:^(BOOL success)
{
NSLog(#"new document opened from iCloud");
}
];
}
}
];
}
}
-
///Note.h
#import <UIKit/UIKit.h>
#interface Note : UIDocument
#property (strong) NSString * noteContent;
#end
-
#import "Note.h"
#implementation Note
#synthesize noteContent;
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
error:(NSError **)outError
{
if ([contents length] > 0)
{
self.noteContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
NSLog(#"loadFromContents1");
NSLog(#"noteContent:%#",noteContent);
NSLog(#"noteContent.length:%d",noteContent.length);
}
else
{
// When the note is first created, assign some default content
self.noteContent = #"Empty";
}
return YES;
}
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0)
{
//self.noteContent = #"Empty";
NSString *FolderName = #"Federal Rules of Civil Procedure";
NSString *fileName = #"supplimentlistdescription.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[FolderName retain];
NSString *fileName1 = [NSString stringWithFormat:#"%#/%#/%#",documentsDirectory,FolderName, fileName];
NSLog(#"fileName1:%#",fileName1);
NSData *data = [[NSData alloc]initWithContentsOfFile:fileName1];
noteContent =[[NSString alloc]initWithData:data encoding:NSMacOSRomanStringEncoding];
NSLog(#"noteContent:%#",noteContent);
NSLog(#"noteContent.length:%d",noteContent.length);
}
return [NSData dataWithBytes:[self.noteContent UTF8String]
length:[self.noteContent length]];
}
#end
Can you please tell me whats can be the problem? Any suggestion will be appreciated. Thanks
I got a same problem like your before.
You should use
for writing
[self.noteContent dataUsingEncoding:NSUTF8StringEncoding];
for reading
self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
Example :
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
if ([contents length] > 0) {
self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
} else {
self.noteContent = #""; // When the note is created we assign some default content
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified"
object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0) {
self.noteContent = #"";
}
return [self.noteContent dataUsingEncoding:NSUTF8StringEncoding];
}

How can I use iCloud to synchronize a .zip file between my apps?

Is it possible to upload a .zip file to iCloud, and then have it be synchronized across all of a user's iOS devices?
If so, how would I go about doing this?
If there is any File size limit, then also mention max. file size allowed.
This is how I synchronized zip files with iCloud .
Steps:
1) http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html
. Refer this link to download zip api which is having code for zipping and unzipping folder.
2) Now all you need to play with NSData.
3) "MyDocument.h" file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSData *zipDataContent;
#end
4)
#import "MyDocument.h"
#implementation MyDocument
#synthesize zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
self.zipDataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return self.zipDataContent;
}
#end
5) Now somewhere in your app you need to zip folder and sync with icloud.
-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSArray *subpaths;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
zipFilePath = [documentsDirectory stringByAppendingPathComponent:zipFilePath];
//NSLog(#"%#",zipFilePath);
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
BOOL successCompressing = [za CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
-(IBAction) iCloudSyncing:(id)sender
{
//***** PARSE ZIP FILE : Pictures *****
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if([self zipFolder:#"Pictures" zipFilePath:#"iCloudPictures"])
NSLog(#"Picture Folder is zipped");
ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"iCloudPictures.zip"];
mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"iCloudPictures"];
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
// NSLog(#"%# %#",zipFilePath,data);
mydoc.zipDataContent = data;
[mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"PictureZip: Synced with icloud");
}
else
NSLog(#"PictureZip: Syncing FAILED with icloud");
}];
}
6) You can unzip data received from iCloud like this.
- (void)loadData:(NSMetadataQuery *)queryData {
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"iCloudPictures"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"Pictures : Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFolder = [documentsDirectory stringByAppendingPathComponent:#"Pics.zip"];
[[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
//NSLog(#"zipFilePath : %#",zipFolder);
NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:#"Pictures"];//iCloudPics
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile: zipFolder] ) {
if( [za UnzipFileTo:outputFolder overWrite:YES] != NO ) {
NSLog(#"Pics : unzip successfully");
}
[za UnzipCloseFile];
}
[za release];
NSError *err;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outputFolder error:&err];
if (files == nil) {
NSLog(#"EMPTY Folder: %#",outputFolder);
}
// Add all sbzs to a list
for (NSString *file in files) {
//if ([file.pathExtension compare:#".jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSLog(#" Pictures %#",file);
// NSFileManager *fm = [NSFileManager defaultManager];
// NSDictionary *attributes = [fm fileAttributesAtPath:[NSString stringWithFormat:#"%#/%#",documentsDirectory,file] traverseLink:NO];
//
// NSNumber* fileSize = [attributes objectForKey:NSFileSize];
// int e = [fileSize intValue]; //Size in bytes
// NSLog(#"%#__%d",file,e);
}
}
else
{
NSLog(#"Pictures : failed to open from iCloud");
[self hideProcessingView];
}
}];
}
}
}
In order to enabling Document storage in iCloud your "document" needs to be encapsulated in a UIDocument object.
Because UIDocument links to a file URL, you can easily create a UIDocument pointing to file://myzipfile.zip and then upload a zip document to iCloud.
I hope this helps
Probably this tutorial can help you more:
http://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

Trying to save images in ipad app bundle from photo library

-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet

How to write a plist on a device? Objective C iphone

I have this code:
#define ALERT(X) {UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info" message:X delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];[alert show];[alert release];}
- (id)readPlist:(NSString *)fileName {
NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"plist"];
plistData = [NSData dataWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
NSLog(#"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
[error release];
}
return plist;
}
- (void)writeToPlist: (NSString*)a
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"data.plist"];
NSMutableArray* pArray = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
[pArray addObject:a];
[pArray writeToFile:finalPath atomically: YES];
ALERT(#"finished");
/* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}
- (void)viewDidLoad {
[super viewDidLoad];
[self writeToPlist:#"this is a test"];
NSArray* the = (NSArray*)[self readPlist:#"data"];
NSString* s = [NSString stringWithFormat:#"%#",the];
ALERT(s);
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
On the simulator the second alert shows the content of the file correctly but on the device it shows nothing?? What's i'm doing wrong? Please show a code/snippet....
The problem is that you could not write a file into mainBundle folder, only Documents folder is accessable on your Device.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];