stringWithContentsOfURL depreciated, help to update to 4.2? - ios4

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];

Related

core data simple fetch request template

I have a small core data base "Guests" and I am trying to get the results from a fetch request template called FetchRequestA, I made a button to trigger in the console the results from the request but I keep on getting a null answer, the request is set to display all guestlastnames that contain a d ? here is the code that i am using :
- (IBAction)fetchA:(id)sender {
NSFetchRequest *request2 = [[[self managedObjectModel] fetchRequestTemplateForName:#"FetchRequestA"] copy];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:#"guestlastname" ascending:YES];
[request2 setSortDescriptors:[NSArray arrayWithObject:sort]];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sort, nil];
[request2 setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:request2 error:&error];
if (fetchedObjects == nil) {
NSLog(#"problem %#", error);
}
for (Guests *guestlastname in fetchedObjects) {
NSLog(#"Fetched Object = %#", guestlastname.guestlastname);
}
}
Am I missing a method ? have perused around but to no avail, thanks in advance.
Here is solution :
(IBAction)gettemplatebutton:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObjectModel* model = [[context persistentStoreCoordinator] managedObjectModel];
NSDictionary* dict = [[NSDictionary alloc]initWithObjectsAndKeys: self.fetchedObjects, #"guestlastname",nil];
NSFetchRequest* request2 = [model fetchRequestFromTemplateWithName:#"FetchRequestA" substitutionVariables: dict];
NSError* error = nil;
NSArray *Guests2 = [context executeFetchRequest:request2 error:&error];
NSString *g3 = #"";
for(NSManagedObject *guestlastname in Guests2)
{
g3 = [g3 stringByAppendingString:[NSString stringWithFormat:#"%#\n", [guestlastname valueForKey:#"guestlastname"]]];
}
self.displaytemplateLabel.text = g3;
[_displaytemplateLabel setNumberOfLines:0];
for (NSManagedObject *guestlastname in Guests2)
{
{
NSLog(#"%#", [guestlastname valueForKey:#"guestlastname"]);
}
}
}
and added #property (nonatomic, retain) NSArray *fetchedObjects; in header file.

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. :)

Saving an object to array using NSMutableDictionary

I have been trying to add an object as an NSMutableDictionary to my array, which I am accessing from another view, and It doesn't seem to work. I want to be able to store the data in a plist which I access from a NSDictionary.
-(void)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
alarmArrayCopy = alarmViewController.alarmsTime;
NSMutableDictionary *newAlarm = [[NSMutableDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[self.navigationController dismissModalViewControllerAnimated:YES];
[newAlarm release];
}
UPDATE: How do I add an NSDictionary to my plist database (my db is an array)?
Here is some new code, I updated the NSMutableDictionary to NSDictionary because in my plist you can only have normal dictionaries not a mutable one. But now it crashed and gives me a Thread 1:Program received signal: "SIGABRT".
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"data.plist"];
// Adding object for alarm to AlarmViewController
NSDictionary *newAlarm = [[NSDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:[NSString stringWithFormat:#"%#", alarmPicker.date] forKey:TIME_KEY];
[newAlarm writeToFile:finalPath atomically:NO];
or
-(IBAction)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
NSString *time = [NSString stringWithFormat:#"%#", alarmPicker.date];
NSString *label = [NSString stringWithFormat:#"%#",labelTextField.text];
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:label, LABEL_KEY,time, TIME_KEY, nil];
self.alarmArrayCopy = alarmViewController.alarmsTime;
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[newAlarm release];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
First, you should use setObject:forKey: method for adding objects to NSMutableDictionary. Second, you should use initWithObjectsAndKeys: method if you are using NSDictionary.
The setValue:forKey is a method of the Key Value Coding protocol. That was described at here “
Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?
”
So, you should do that,
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:
labelTextField.text, LABEL_KEY,
alarmPicker.date, TIME_KEY, nil];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
I am not quite sure, but I guess your error is because you can't send an instance of NSDate object to setValue:forKey method. You may use either setObject:forKey or change NSDate to NSString by [NSString stringWithFormat:"%#", alarmPicker.date].
Hope that helps.

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

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];

How do you use MPMediaItemPropertyPersistentID to play music in iPhone Music Player Framework?

My code sucessfully catalogs song names and ID's for my the entire music library. However, it will not actually play a song using this methodology and the console displays the following:
Message playbackState timed out.
Message nowPlayingItem timed out.
self.musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongName = [[NSMutableArray alloc] init];
SongItem = [[NSMutableArray alloc] init];
NSString *songTitle;
NSString *songID;
//Collect names & ID for entire music library & put into arrays
for (MPMediaItem *song in itemsFromGenericQuery) {
songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
[SongName addObject:songTitle];
songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
[SongItem addObject:songID];
}
NSLog (#"%#", [SongName objectAtIndex:1]);
NSLog (#"%#", [SongItem objectAtIndex:1]);
// Play the second song in the list
MPMediaItemCollection *collection = [MPMediaItemCollection collectionWithItems:[NSArray arrayWithObject:[SongItem objectAtIndex:1]]];
[self.musicPlayer setQueueWithItemCollection:collection];
[self.musicPlayer play];
Once again, I'll answer my own question. The issue was that collectionWithItems: expects an array of MPMediaItems, not an array of MPMediaItemPropertyPersistentIDs. Here is the working code for anyone who may have the same problem:
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongItem = [[NSMutableArray alloc] init];
for (MPMediaItem *song in itemsFromGenericQuery) {
NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
//NSLog (#”%#”, songTitle);
songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
//NSLog (#”%#”, songID);
[SongItem addObject:songID];
}
//Choose the first indexed song
NSString *selectedTitle = [SongItem objectAtIndex:0];
//Use the MPMediaItemPropertyPersistentID to play the song
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:selectedTitle forProperty:MPMediaItemPropertyPersistentID];
MPMediaQuery *mySongQuery = [[MPMediaQuery alloc] init];
[mySongQuery addFilterPredicate: predicate];
[musicPlayer setQueueWithQuery:mySongQuery];
[musicPlayer play];

Resources