NSException When repeating NSTask - objective-c

I have this code that is suppose to check certain settings and log the results. The first setting check works correctly but the next one fails. Here is the code block:
//init classes
CocoaLogging *logFile = [[CocoaLogging alloc]init];
NSString * result;
NSInteger * state;
NSPipe *pipe=[[NSPipe alloc] init];
NSFileHandle *handle;
NSString * cmd = [NSString stringWithFormat:#"%#", #"/usr/bin/defaults"];
//Start logging
NSString *logText;
NSString *logPath;
BOOL logSuccess;
NSLog(#"Start Settings Enforcer");
logPath = [NSString stringWithFormat:#"%#%#", NSHomeDirectory(), LOGFILE_PATH];
if (! [[NSFileManager defaultManager] fileExistsAtPath:logPath isDirectory:NO])
{
logSuccess = [logFile createLogFile:logPath];
if (logSuccess)
{
logText = [NSString stringWithFormat:#"%#", #"Start Settings Enforcer"];
[logFile makeLogEntry:logText to:logPath];
}
}
else
{
logPath = [NSString stringWithFormat:#"%#%#", NSHomeDirectory(), LOGFILE_PATH];
logText = [NSString stringWithFormat:#"%#", #"Start Settings Enforcer"];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
//check status of firewall
//defaults read "/Library/Preferences/com.apple.alf" globalstate
//array of commandline args
NSMutableArray *firewallArgs = [[NSMutableArray alloc]initWithObjects:#"-currentHost", #"read", #"/Library/Preferences/com.apple.alf", #"globalstate", nil];
//init the task
NSTask *firewall=[[NSTask alloc] init];
//define the command to run
[firewall setLaunchPath:cmd];
[firewall setArguments:firewallArgs];
[firewall setStandardOutput:pipe];
handle=[pipe fileHandleForReading];
//run the command
[firewall launch];
// convert NSData -> NSString
result = [[NSString alloc] initWithData:[handle readDataToEndOfFile]encoding:NSASCIIStringEncoding];
state = [result intValue];
NSLog(#"%#", result);
if (state == 1)
{
NSLog(#"firewall is on");
logText = [NSString stringWithFormat:#"%#", #"firewall is on"];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
else
{
NSLog(#"firewall is off");
logText = [NSString stringWithFormat:#"%#", #"firewall is off"];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
[firewallArgs removeAllObjects];
[handle closeFile];
[firewall terminate];
//check screensaver on
//defaults read ~/Library/Preferences/com.apple.screensaver askForPassword
NSString * plistPath = [NSString stringWithFormat:#"%#", #"~/Library/Preferences/com.apple.screensaver"];
plistPath = [plistPath stringByExpandingTildeInPath];
//array of commandline args
NSMutableArray *ssOnArgs = [[NSMutableArray alloc]initWithObjects:#"read", plistPath, #"askForPassword", nil];
//init the task
NSTask *ssOn=[[NSTask alloc] init];
//define the command to run
[ssOn setLaunchPath:cmd];
[ssOn setArguments:ssOnArgs];
[ssOn setStandardOutput:pipe];
handle=[pipe fileHandleForReading];
//run the command
[ssOn launch];
// convert NSData -> NSString
result = [[NSString alloc] initWithData:[handle readDataToEndOfFile]encoding:NSASCIIStringEncoding];
state = [result intValue];
if (state == 1)
{
NSLog(#"screensaver is on");
logText = [NSString stringWithFormat:#"%#", #"screensaver is on"];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
else
{
NSLog(#"screensaver is off");
logText = [NSString stringWithFormat:#"%#", #"screensaver is off"];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
NSLog(#"Check-in complete");
logText = [NSString stringWithFormat:#"%#", #"Check-in complete."];
logSuccess = [logFile makeLogEntry:logText to:logPath];
}
return 0;
}
Here is the error:
2014-03-31 12:58:11.630 SettingsEnforcer[5379:303] * Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: ' -[NSConcreteFileHandle fileDescriptor]: No such process'
** First throw call stack:
(
0 CoreFoundation 0x00007fff8ce4825c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8b075e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8ce4810c +[NSException raise:format:] + 204
3 Foundation 0x00007fff8ba9a29d -[NSConcreteFileHandle fileDescriptor] + 30
4 Foundation 0x00007fff8bb2fb97 -[NSConcreteTask launchWithDictionary:] + 2114
5 SettingsEnforcer 0x0000000100001e1e main + 2126
6 libdyld.dylib 0x00007fff91e555fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I hope someone smarter than I can spot the error.

You are recycling the NSPipe instance. Create a new pipe for the second task.

Related

Objective-C: How to remove multiple files with admin privileges?

I am trying to remove multiple files using apple script (given below) but it is not working and giving the following error:
Expected expression but found unknown token.
Here is my code:
{
///this string will be a contact of all the paths saperated by ' '
NSString* removingLocationInString = #"";
///for loop in order to concat all the string(paths) in one string
for (NSString* str in locations) {
removingLocationInString = [NSString stringWithFormat:#"%# \"%#\"", removingLocationInString, str];
}
///creating the command that will be run from apple script
///e.g. rm "~/user/vikas/desktop/file.txt" "~/user/vikas/desktop/file2.txt"
NSString* command = [NSString stringWithFormat:#"rm %#", removingLocationInString];
[self runScriptAsAdmin:command];
}
-(BOOL)runScriptAsAdmin:(NSString*) fullScript
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: #"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
#"-c" ,
[NSString stringWithFormat:#"%#", fullScript],
nil];
NSString * output = nil;
NSString * processErrorDescription = nil;
NSDictionary *errorInfo = [NSDictionary new];
NSString *script = [NSString stringWithFormat:#"do shell script \"%#\" with administrator privileges", fullScript];
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];
// Check errorInfo
if (! eventResult)
{
// Describe common errors
NSString *errorDescription = nil;
if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
{
NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
if ([errorNumber intValue] == -128)
errorDescription = #"The administrator password is required to do this.";
}
// Set error message from provided message
if (errorDescription == nil)
{
if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
errorDescription = (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
}
return NO;
}
else
{
// Set output to the AppleScript's output
NSString *output = [eventResult stringValue];
return YES;
}
return NO;
}
Here is the script that is being generated
do shell script "rm "/Users/vikas/.Trash/.DS_Store"
"/Users/vikas/.Trash/SimpleCocoaBrowser 2.zip"
"/Users/vikas/.Trash/SimpleCocoaBrowser 3.zip"
"/Users/vikas/.Trash/SimpleCocoaBrowser 4 4.55.07 pm.zip"
"/Users/vikas/.Trash/SimpleCocoaBrowser 4.zip"" with administrator
privileges
In runScriptAsAdmin function add the following line:
/// if there are " in script then then make it \"
fullScript = [fullScript stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
The actual apple script should be as follows:
do shell script "rm \"/Users/vikas/.Trash/SimpleCocoaBrowser 2.zip\"
\"/Users/vikas/.Trash/SimpleCocoaBrowser 3.zip\"
\"/Users/vikas/.Trash/SimpleCocoaBrowser 4.zip\"" with administrator
privileges

App crashing after selecting audio in iOS 7, fine on iOS 6

When selecting a song from the users library on either iPhone or iPad devices running iOS7 my app crashes out
The line it stops on is
FourCharCode formatID = audioDesc->mFormatID;
With a EXC_BAD_ACCESS code
Trying to check the console for more info, this is the last step it mentions;
appMake[8392:60b] Select music AssetUrl = (null)
Code below for the export session part;
- (void)exportAssetAsSourceFormat:(MPMediaItem *)item {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:songAsset
presetName:AVAssetExportPresetPassthrough];
NSArray *tracks = [songAsset tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack *track = [tracks objectAtIndex:0];
id desc = [track.formatDescriptions objectAtIndex:0];
const AudioStreamBasicDescription *audioDesc = CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)desc);
FourCharCode formatID = audioDesc->mFormatID;
NSString *fileType = nil;
NSString *ex = nil;
switch (formatID) {
case kAudioFormatLinearPCM:
{
UInt32 flags = audioDesc->mFormatFlags;
if (flags & kAudioFormatFlagIsBigEndian) {
fileType = #"public.aiff-audio";
ex = #"aif";
} else {
fileType = #"com.microsoft.waveform-audio";
ex = #"wav";
}
}
break;
case kAudioFormatMPEGLayer3:
fileType = #"com.apple.quicktime-movie";
ex = #"mp3";
break;
case kAudioFormatMPEG4AAC:
fileType = #"com.apple.m4a-audio";
ex = #"m4a";
break;
case kAudioFormatAppleLossless:
fileType = #"com.apple.m4a-audio";
ex = #"m4a";
break;
default:
break;
}
exportSession.outputFileType = fileType;
NSString *exportPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:[EXPORT_NAME stringByAppendingPathExtension:ex]] retain];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
NSLog(#"export session completed");
//return YES;
[self performSelectorOnMainThread:#selector(gotoMainView:)
withObject:[EXPORT_NAME stringByAppendingPathExtension:ex]
waitUntilDone:NO];
} else {
NSLog(#"export session error");
//return NO;
}
[exportSession release];
}];
[pool release];
}
Media picker code;
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
// Dismiss the media item picker.
[self dismissModalViewControllerAnimated: YES];
if ([mediaItemCollection count] < 1) {
return;
}
[selectedItem release];
selectedItem = [[[mediaItemCollection items] objectAtIndex:0] retain];
NSURL* filePath = [selectedItem valueForProperty: MPMediaItemPropertyAssetURL];
NSLog(#"Select music AssetUrl = %#", filePath);
[viewLoading setHidden:NO];
[self UnloadSound];
[NSThread detachNewThreadSelector:#selector(exportAssetAsSourceFormat:) toTarget:self withObject:selectedItem];
}

What's the easiest way to extract some element from this URL [duplicate]

This question already has answers here:
Extract part of URL
(2 answers)
Parse NSURL query property
(17 answers)
Closed 10 years ago.
This is the URL
assets-library://asset/asset.JPG?id=CF2AF034-9CF7-4472-9185-5EEFA1614A07&ext=JPG
I want to get:
CF2AF034-9CF7-4472-9185-5EEFA1614A07
How would I do that? Is there a method in NSURL that can accomplish this?
This is what I did:
-(NSString *) fgetTokenWithPre:(NSString *) pre andPost:(NSString*) post startSearch:(NSUInteger) start
{
NSRange rangeToSearch;
rangeToSearch.location = start;
rangeToSearch.length =self.length-rangeToSearch.location;
NSRange preRange = [self rangeOfString:self options:NSCaseInsensitiveSearch range:rangeToSearch];
Result
(lldb) po self
$6 = 0x1e54f130 id=00000000-0000-0000-0000-0000000005E9&ext=JPG
(lldb) po pre
$7 = 0x0021d8a0 id=
(lldb) p preRange
(NSRange) $8 = location=0, length=47
But that doesn't make sense. It's obvious that self is 47 length and I am looking for pre that's only 3 length. So how come preRange is [0,47]?
The below code block will probably do what you're after
__block NSString *queryID;
[[[url query] componentsSeparatedByString:#"&"] enumerateObjectsUsingBlock:^(NSString *queryString, NSUInteger idx, BOOL *stop) {
NSArray *query = [queryString componentsSeparatedByString:#"="];
if ([query[0] isEqualToString:#"id"]) {
queryID = query[1];
*stop = YES;
}
}];
NSLog(#"ID value = %#", queryID);
However, it's not very safe. It makes assumptions about well formed URL's and that there will be (at least) 2 values in the query array.
NSUrl *asseturl = [NSURL URLWithString:#"assets-library://asset/asset.JPG?id=CF2AF034-9CF7-4472-9185-5EEFA1614A07&ext=JPG"];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref) {
largeimage = [UIImage imageWithCGImage:iref];
[largeimage retain];
}
};
//
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"booya, cant get image - %#",[myerror localizedDescription]);
};
if(mediaurl && [mediaurl length] && ![[mediaurl pathExtension] isEqualToString:AUDIO_EXTENSION])
{
[largeimage release];
NSURL *asseturl = [NSURL URLWithString:mediaurl];
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];
}
}

Error: index 1 beyond bounds [0 .. 0]

I am a rookie in Xcode and I have been using the UITableViewController which shows this error.
This is the error message:
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
* First throw call stack:
(0x1c91012 0x10cee7e 0x1c330b4 0x36d0 0xc58d5 0xc5b3d 0xacce83 0x1c50376 0x1c4fe06 0x1c37a82 0x1c36f44 0x1c36e1b 0x1beb7e3 0x1beb668 0x1665c 0x2132 0x2065)
libc++abi.dylib: terminate called throwing an exception
(lldb)
This is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row0"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 1) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row1"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while (objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 2) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row2"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 3) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row3"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
}
When I click on the second cell (index.row == 1) this error would occur.
I have used breakpoint and the error was on the line:
"NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];"
Please Help!
Swift 4
after more time i am get the love for this Error 😄
when you use the tableView from the storyboard and implementing in your code :
hint that and compare :
between the number of section and numberOfRowsInSection == storyboard and code
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
You have an array and you have either 0 or 1 elements in it. Now you are trying to extract 2nd element from it, [0] is first, and [1] is second.
EDIT:
As you are not sure when the array will contain 1 or more objects. Therefore you can use as:
NSString *nn=nil;
if([arrayDataFromServer2 count]>1){
nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
}

Deleting Objects from Coredata

In my app I have a Place entity that contains reviews and featured objects at the minute my app is constantly refreshing these everytime i parse my xml data which is fine however I need to delete the review and featued objects before they are re parsed. My code is as follows and I believe I need to delete the objects in the parseXML method at the top:
-(void)parseXML:(NSString*)xml{
TBXML * tbxml = [TBXML tbxmlWithXMLString:xml];
if(tbxml.rootXMLElement){
[self traverseElement:tbxml.rootXMLElement];
if(self.tempItem){
NSLog(#"Ending Application");
[self configurePlaceChildrenAndSave];
[self startGeoCodingQueue];
}
}
}
-(void)fireGeocoder:(BSForwardGeocoder*)g{
NSLog(#"Begining FGC for %# (%#)",g.searchQuery,g.metaData);
[g findLocation];
}
-(void)startGeoCodingQueue{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:kGeoCoderInProgress];
int i = 0;
BSForwardGeocoder * fgc;
NSArray * a = [CoreDataBasicService fetchResultsForEnity:#"Place" andSortDiscriptor:#"name" Ascending:YES];
for (Place * p in a) {
if(p.latitude && p.longitude)continue;//skip geocoding if location data exists
fgc = [[BSForwardGeocoder alloc] initWithDelegate:self];
fgc.metaData = p.name;
fgc.searchQuery = p.postcode;
NSLog(#"gc:%i-%i",i,[a count]);
if([a count] == i+1){
fgc.last = YES;
}
float delay = (float)i*kGeoCoderDelay;
[self performSelector:#selector(fireGeocoder:) withObject:[fgc autorelease] afterDelay:delay];
fgc = nil;
i++;
}
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:i] forKey:kGeoCoderCompletedKey];
}
-(void)finishedGeocoding{
[[NSUserDefaults standardUserDefaults] setValue:[NSDate date] forKey:kGeoCoderlastRanKey];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO] forKey:kGeoCoderInProgress];
[[NSNotificationCenter defaultCenter] postNotificationName:kGeoCoderNotificationName object:nil];
}
-(void)forwardGeocoderError:(BSForwardGeocoder *)geocoder errorMessage:(NSString *)errorMessage{
NSLog(#"EX ERROR: GEOCODER FAILED - %#",errorMessage);
if(geocoder.last)[self finishedGeocoding];
}
- (void)forwardGeocoderFoundLocation:(BSForwardGeocoder*)geocoder
{
if(geocoder.status == G_GEO_SUCCESS)
{
BSKmlResult *result = [geocoder.results lastObject];
if(!result)return;
//[self.fowardGeocodingQueue setObject:[NSString stringWithString:value] forKey:self.tempItem.name];
Place * p = [CoreDataBasicService fetchPlaceNamed:geocoder.metaData];
p.latitude = [NSNumber numberWithFloat:result.latitude];
p.longitude = [NSNumber numberWithFloat:result.longitude];
[CoreDataBasicService saveChanges];
//NSLog(#"%# - %f,%f",p2.name,p2.latitude,p2.longitude);
NSLog(#"completed Foward geocoding for '%#' (%#) [%f,%f]",geocoder.metaData,geocoder.searchQuery,[p.latitude floatValue],[p.longitude floatValue]);
if(geocoder.last)[self finishedGeocoding];
}
else {
NSString *message = #"";
switch (geocoder.status) {
case G_GEO_BAD_KEY:
message = #"The API key is invalid.";
break;
case G_GEO_UNKNOWN_ADDRESS:
message = [NSString stringWithFormat:#"Could not find %#", geocoder.searchQuery];
break;
case G_GEO_TOO_MANY_QUERIES:
message = #"Too many queries has been made for this API key.";
break;
case G_GEO_SERVER_ERROR:
message = #"Server error, please try again.";
break;
default:
break;
}
NSLog(#"ERROR: GEOCODER FAILED - %#",message);
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Information"
// message:message
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles: nil];
// [alert show];
// [alert release];
}
}
-(void)configurePlaceChildrenAndSave{
if(self.tempReviewArray.count==0 && self.tempReview)[self.tempReviewArray addObject:self.tempReview];
if(self.tempFeatureArray.count==0 && self.tempFeature)[self.tempFeatureArray addObject:self.tempFeature];
[self.tempItem setReviews:self.tempReviewArray];
[self.tempItem setFeatured:self.tempFeatureArray];
self.tempReviewArray = nil;
self.tempReview = nil;
self.tempFeatureArray = nil;
self.tempFeature = nil;
[CoreDataBasicService saveChanges];
self.tempItem = nil;
}
-(NSString*)formatKeyForCoreData:(NSString*)elementKey{
return [elementKey stringByReplacingOccurrencesOfString:#"-" withString:#""];
}
-(NSDate*)convertStringDateToDate:(NSString*)stringDate{
NSDateFormatter * df = [[NSDateFormatter alloc] init];
NSLog(#"DATE:%#",stringDate);
[df setDateFormat:#"y-M-d'T'H:m:s'Z'"];
NSDate * d = [df dateFromString:stringDate];
[df release];
return d;
}
-(Place*)getPlaceForName:(NSString*)name{
NSPredicate * pred = [NSPredicate predicateWithFormat:#"name = %#",name];
NSArray * results = [CoreDataBasicService fetchResultsForEnity:#"Place" WithPredicate:pred andSortDiscriptor:#"identifier" Ascending:YES];
return [results lastObject];
}
-(void)traverseElement:(TBXMLElement *)element {
do {
// Display the name of the element
NSString * value = [TBXML textForElement:element];
NSLog(#"%#-'%#'",[TBXML elementName:element],value);
// Obtain first attribute from element
NSString * ele = [TBXML elementName:element];
if([ele isEqualToString:#"place"]){
if(self.tempItem){
//GEOCODER HERE
[self configurePlaceChildrenAndSave];
}
//CREATE NEW CD ITEM HER
if(dataBaseExits){
TBXMLElement * idElement = [TBXML childElementNamed:#"name" parentElement:element];
Place * p = [self getPlaceForName:[NSString stringWithFormat:#"%#",[TBXML textForElement:idElement]]];
if(p){
[self setTempItem:p];
TBXMLElement * reviewsElement = [TBXML childElementNamed:#"reviews" parentElement:element];
if(reviewsElement){
self.tempItem.reviews = nil;
[CoreDataBasicService saveChanges];
[self traverseElement:reviewsElement];
}
TBXMLElement * promosElement = [TBXML childElementNamed:#"featured-places" parentElement:element];
if(promosElement){
self.tempItem.featured = nil;
[CoreDataBasicService saveChanges];
[self traverseElement:promosElement];
}
[CoreDataBasicService saveChanges];
continue;
}