how to store file contents to iphone's internal memory using xcode? - ios4

how to store file contents to iphone's internal memory using xcode ?
I want to store XML file to iPhone's internal memory.

You can read hold the xml data in NSData and store the file in private folder ( avaible only for application )
below is code for saving file
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
[str appendString:documentsDirectory];
[str appendString:#"/"];
[str appendString:aName];
NSFileManager *fileManager = [NSFileManager defaultManager];
[/*NSData*/ writeToFile:str atomically:YES];
if(str)
{
[str release];
str = nil;
}
if(fileManager)
{
[fileManager release];
fileManager = nil;
}
[pool release];

Related

downloaded video - AFHTTPRequestOperation vs. NSURLSessionDownloadTask

I try to update my existing download-model, so I have replaced my old code:
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *data = [[NSData alloc] initWithData:responseObject];
[data writeToFile:video2Save.localFilePath atomically:YES];
video2Save.downloadComplete = YES;
[YEPersistentModelHelper saveData:_downloadVideos ToDiskWithIdentifier:persistentIdDownloadedVideos];
NSLog(#"file downloading complete : %#", video2Save.localFilePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"file downloading error : %#", [error localizedDescription]);
}];
[downloadRequest start];*/
with the following:
NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4",video2Save.videoVersionId]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
video2Save.localFilePath = [[filePath filePathURL] absoluteString];
video2Save.downloadComplete = YES;
[YEPersistentModelHelper saveData:_downloadVideos ToDiskWithIdentifier:persistentIdDownloadedVideos];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err = nil;
NSDictionary *att = [fileManager attributesOfItemAtPath:video2Save.localFilePath error:&err];
NSLog(#"NSDictionary: %#", att);
}];
[downloadTask resume];
And it seems to work fine. The complete-block is executed & the file exists at the traced target.
The problem is, that I am no longer available to play the video! I use the MPMoviePlayerController which throws this useful error:
_itemFailedToPlayToEnd: { kind = 1; new = 2; old = 0; }
The only difference seems to be the file-permissions. The first one adds a "staff"-group & everyone is allowed to read while the second only grants access for "me". But even if I change it in the finder I am not able to play it...
Does anyone has an idea!?
to save location file use path no absoluteString
video2Save.localFilePath = [[filePath filePathURL] absoluteString];
don't call absoluteString even to play.. just use the path
like this for example to call the video
NSURL *FilePathURL = [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:fileToCheck]];
[[myvideoCalss :[FilePathURL path]]

Lightweight migration with iCloud

I have an app that can be run two ways: Using Local Storage or using iCloud. When I use local storage, my lightweight migration works fine, but when I choose iCloud, it causing all my data to be lost. Here is the code I use to initialize the persistent store coordinator:
NSMutableDictionary *options = [NSMutableDictionary dictionary];
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *ubContainer = [fm URLForUbiquityContainerIdentifier:nil];
NSURL *logsDir = [ubContainer URLByAppendingPathComponent:#"logsDir"];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
if ([[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsUseICloud]) {
// Construct the dictionary that tells Core Data where the transaction log should be stored
[options setObject:#"comcompanyappname" forKey:NSPersistentStoreUbiquitousContentNameKey];
[options setObject:logsDir forKey:NSPersistentStoreUbiquitousContentURLKey];
}
// Read in xcdatamodeld
model = [NSManagedObjectModel mergedModelFromBundles:nil];
psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSURL *nosyncDir = [ubContainer URLByAppendingPathComponent:#"appname.nosync"];
NSURL *storeURL;
if (ubContainer) {
[fm createDirectoryAtURL:nosyncDir withIntermediateDirectories:YES attributes:nil error:nil];
storeURL = [nosyncDir URLByAppendingPathComponent:#"store.data"];
}
else{
NSString *path = [self itemArchivePath];
storeURL = [NSURL fileURLWithPath:path];
}
NSError *error = nil;
[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
[NSException raise:#"Open failed" format:#"Reason: %#", [error localizedDescription]];
}
[psc unlock];
// Create the managed object context
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:psc];
[context setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
// The managed object context can manage undo, but we don't need it
[context setUndoManager:nil];

Copy item from iPod Library

I'm trying to copy an item from the iPod Library to my local storage space - for later playback. I've got the item URl but it's (ipod-library://item/item.mp3?id=2398084975506389321) any idea how to access the actual file?
Thanks,
Rick
This will work https://gist.github.com/3304992
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
NSString *tempPath = NSTemporaryDirectory();
int i=1;
for (MPMediaItem *theItem in mediaItemCollection.items) {
NSURL *url = [theItem valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = #"com.apple.coreaudio-format";
NSString *fname = [[NSString stringWithFormat:#"%d",i] stringByAppendingString:#".caf"];
++i;
NSString *exportFile = [tempPath stringByAppendingPathComponent: fname];
exporter.outputURL = [NSURL fileURLWithPath:exportFile];
[exporter exportAsynchronouslyWithCompletionHandler:^{
//Code for completion Handler
}];
}
[picker dismissViewControllerAnimated:YES completion:Nil];
}
use MPMediaPickerController to pick the media
This is how I'm doing it in Objective-C:
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudio.h>
// or [NSURL URLWithString:#"ipod-library://item/item.mp3?id=2398084975506389321"]
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
NSMutableData *data = [[NSMutableData alloc] init];
const uint32_t sampleRate = 16000;
const uint16_t bitDepth = 16;
const uint16_t channels = 2;
NSDictionary *opts = [NSDictionary dictionary];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:assetURL options:opts];
AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:asset error:NULL];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
[NSNumber numberWithFloat:(float)sampleRate], AVSampleRateKey,
[NSNumber numberWithInt:bitDepth], AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
[NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
nil];
AVAssetReaderTrackOutput *output = [[AVAssetReaderTrackOutput alloc] initWithTrack:[[asset tracks] objectAtIndex:0] outputSettings:settings];
[asset release];
[reader addOutput:output];
[reader startReading];
// read the samples from the asset and append them subsequently
while ([reader status] != AVAssetReaderStatusCompleted) {
CMSampleBufferRef buffer = [output copyNextSampleBuffer];
if (buffer == NULL) continue;
CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(buffer);
size_t size = CMBlockBufferGetDataLength(blockBuffer);
uint8_t *outBytes = malloc(size);
CMBlockBufferCopyDataBytes(blockBuffer, 0, size, outBytes);
CMSampleBufferInvalidate(buffer);
CFRelease(buffer);
[data appendBytes:outBytes length:size];
free(outBytes);
}
[output release];
Here data will contain the raw PCM data of the track. Please note that you cannot directly access the file of a song or video, only its data through this method. You can compress it using e. g. FLAC (that's how I'm processing it in my tweak).
Since MonoTouch has an 1:1 mapping to Objective-C class and method names, this should be fairly easy to copy over. :)

stringWithContentsOfURL depreciated, help to update to 4.2?

Hello
Could anyone help me update this snippent to iOS 4.2:
-(void) whatever{
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: #"http://www.objectgraph.com/contact.html"]] dataUsingEncoding:NSUTF8StringEncoding];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser search:#"//h3"]; // get the page title - this is xpath notation
TFHppleElement *element = [elements objectAtIndex:0];
NSString *myTitle = [element content];
NSLog(myTitle);
[xpathParser release];
[htmlData release];}
The only part that needs updating is below, you can effectivly forget the rest:
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: #"http://www.objectgraph.com/contact.html"]] dataUsingEncoding:NSUTF8StringEncoding];
"stringWithContentsOfURL" has been deprechiated so what would be the updated version?
Thanks
You should use
+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
And use it like that. Replace
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: #"http://www.objectgraph.com/contact.html"]] dataUsingEncoding:NSUTF8StringEncoding];
by
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: #"http://www.objectgraph.com/contact.html"]] encoding:NSUTF8StringEncoding error:nil];

Printing Core Data

I'm working on a program and I have created a fetch request to grab the data that I need to print. I'm able to log information like this:
2010-10-03 16:57:10.362 lzshow7.2[2537:10b] <NSManagedObject: 0x2ca120> (entity: Song; id: 0x2afcb0 <x-coredata://CF5A85CE-BE0F-4ADC-979A-7F4214A8FB19/Song/p9> ; data: {
cueName = Freedom;
cueNo = 014;
cueNotes = nil;
songToInstrument = "<relationship fault: 0x2b1800 'songToInstrument'>";
})
How do I seperate the properties like cueName, cueNo, cueNotes out to be printed?
Here is the fetch request:
//Managed object context???
NSLog(#"setting Managed object stuff");
NSManagedObjectContext *context=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
NSLog(#"Second line of Managed object stuff");
//fetch request:
NSLog(#"Starting to fetch:");
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Song" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"cueNo" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
for (id obj in mutableFetchResults)
NSLog(#"%#", obj);
NSLog(#"finished looping");
//Error handling
if (mutableFetchResults == nil) {
// Handle the error.
}
//[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
}
Any help would be greatly appreciated.
Thank you,
Loren
You use basically the opposite of how you stored the values in your managedObject
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSLog(#"%# %# %#", name, number, notes);
if you've created a custom Class of your entity you could add this method:
- (NSString *)description {
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSString *returnString = [NSString stringWithFormat:#"%# %# %#", name, number, notes];
return returnString;
}
With this method you can just use NSLog(#"%#", object); to get a nice formatted output

Resources