Not receiving notification dispatch_group_notify - ios

I am currently using a dispatch_group to get notify when all concurrent tasks are done. I am offloading some heavy tasks on one concurrent queue within the [TWReaderDocument documentFileURL:url withCompletionBlock:] class method.
I have implemented the following code but never received any notification. I don't see what i am potentially doing wrong in the below code:
dispatch_group_t readingGroup = dispatch_group_create();
NSFileManager* manager = [NSFileManager defaultManager];
NSString *docsDir = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Data"];
NSDirectoryEnumerator *dirEnumerator = [manager enumeratorAtURL:[NSURL fileURLWithPath:docsDir]
includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey,
NSURLIsDirectoryKey,nil]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:nil];
// An array to store the all the enumerated file names in
NSMutableArray *arrayFiles;
// Enumerate the dirEnumerator results, each value is stored in allURLs
for (NSURL *url in dirEnumerator) {
// Retrieve the file name. From NSURLNameKey, cached during the enumeration.
NSString *fileName;
[url getResourceValue:&fileName forKey:NSURLNameKey error:NULL];
// Retrieve whether a directory. From NSURLIsDirectoryKey, also cached during the enumeration.
NSNumber *isDirectory;
[url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if (![isDirectory boolValue]) {
dispatch_group_enter(readingGroup);
TWReaderDocument* doc = [TWReaderDocument documentFileURL:url withCompletionBlock:^(BOOL success) {
dispatch_group_leave(readingGroup);
}];
[arrayFiles addObject:doc];
}
else if ([[[fileName componentsSeparatedByString:#"_" ] objectAtIndex:0] isEqualToString:#"XXXXXX"]) {
TreeItem* treeItem = [[TreeItem alloc] init];
arrayFiles = [NSMutableArray arrayWithCapacity:10];
treeItem.child = arrayFiles;
treeItem.nodeName = [[fileName componentsSeparatedByString:#"_" ] lastObject];
[self addItem:treeItem];
}
}
dispatch_group_notify(readingGroup, dispatch_get_main_queue(), ^{ // 4
NSLog(#"All concurrent tasks completed");
});
Does the dispatch_group_enter and dispatch_group_leave have to be executed on the same thread?
EDIT
The code snippet of my factory method might help aswell:
+ (TWReaderDocument *)documentFileURL:(NSURL *)url withCompletionBlock:(readingCompletionBlock)completionBlock{
TWReaderDocument * twDoc = [[TWReaderDocument alloc] init];
twDoc.status = ReaderDocCreated;
twDoc.doc = [ReaderDocument withDocumentFilePath:[url path] withURL:url withLoadingCompletionBLock:^(BOOL completed) {
twDoc.status = completed ? ReaderDocReady : ReaderDocFailed;
completionBlock(completed);
}];
return twDoc;
}
TWReaderDocument is a wrapper class that call internally the following methods of a third-party library (it is a PDF reader)
+ (ReaderDocument *)withDocumentFilePath:(NSString *)filePath withURL:(NSURL*)url withLoadingCompletionBLock:(readingCompletionBlock)completionBlock{
ReaderDocument *document = [[ReaderDocument alloc] initWithFilePath:filePath withURL:url withLoadingCompletionBLock:[completionBlock copy]];
return document;
}
- (id)initWithFilePath:(NSString *)fullFilePath withURL:(NSURL*)url withLoadingCompletionBLock:(readingCompletionBlock)completionBlock {
id object = nil; // ReaderDocument object;
if ([ReaderDocument isPDF:fullFilePath] == YES) // File must exist
{
if ((self = [super init])) // Initialize superclass object first
{
_fileName = [ReaderDocument relativeApplicationFilePath:fullFilePath]; // File name
dispatch_async([ReaderDocument concurrentLoadingQueue], ^{
self.guid = [ReaderDocument GUID]; // Create a document GUID
self.password = nil; // Keep copy of any document password
self.bookmarks = [NSMutableIndexSet indexSet]; // Bookmarked pages index set
self.pageNumber = [NSNumber numberWithInteger:1]; // Start on page 1
CFURLRef docURLRef = (__bridge CFURLRef)url;// CFURLRef from NSURL
self.fileURL = url;
CGPDFDocumentRef thePDFDocRef = CGPDFDocumentCreateX(docURLRef, self.password);
BOOL success;
if (thePDFDocRef != NULL) // Get the number of pages in the document
{
NSInteger pageCount = CGPDFDocumentGetNumberOfPages(thePDFDocRef);
self.pageCount = [NSNumber numberWithInteger:pageCount];
CGPDFDocumentRelease(thePDFDocRef); // Cleanup
success = YES;
}
else // Cupertino, we have a problem with the document
{
// NSAssert(NO, #"CGPDFDocumentRef == NULL");
success = NO;
}
NSFileManager *fileManager = [NSFileManager new]; // File manager instance
self.lastOpen = [NSDate dateWithTimeIntervalSinceReferenceDate:0.0]; // Last opened
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:fullFilePath error:NULL];
self.fileDate = [fileAttributes objectForKey:NSFileModificationDate]; // File date
self.fileSize = [fileAttributes objectForKey:NSFileSize]; // File size (bytes)
completionBlock(success);
});
//[self saveReaderDocument]; // Save the ReaderDocument object
object = self; // Return initialized ReaderDocument object
}
}
return object;
}

It's hard to say what's going on here without knowing more about TWReaderDocument, but I have a suspicion...
First off, no, dispatch_group_enter and dispatch_group_leave do not have to be executed on the same thread. Definitely not.
My best guess based on the info here would be that for some input, [TWReaderDocument documentFileURL:withCompletionBlock:] is returning nil. You might try this instead:
if (![isDirectory boolValue]) {
dispatch_group_enter(readingGroup);
TWReaderDocument* doc = [TWReaderDocument documentFileURL:url withCompletionBlock:^(BOOL success) {
dispatch_group_leave(readingGroup);
}];
// If the doc wasn't created, leave might never be called.
if (nil == doc) {
dispatch_group_leave(readingGroup);
}
[arrayFiles addObject:doc];
}
Give that a try.
EDIT:
It's exactly as I expected. There are cases in which this factory method will not call the completion. For instance:
if ([ReaderDocument isPDF:fullFilePath] == YES) // File must exist
If -isPDF: returns NO the completionBlock will never be called, and the returned value will be nil.
Incidentally, you should never compare something == YES. (anything non-zero is equivalent to YES, but YES is defined as 1. Just do if ([ReaderDocument isPDF:fullFilePath]). It's equivalent, and safer.

Related

Use iclems/iOS-htmltopdf to generate multiple pdf from multiple html file

I'm wrapping a for loop for function to enable multiple html to multiple pdf conversion:
for (int i=0; i<= 47; i++) {
NSString *inputHTMLfileName = [NSString stringWithFormat:#"wkhtml_tempfile_%d",j];
NSString *outputPDFfileName = [NSString stringWithFormat:#"~/Documents/%d_delegateDemo%d.pdf",loop,j];
NSURL *htmlFileUrl = [[NSBundle mainBundle]
URLForResource:inputHTMLfileName withExtension:#"html"];
// Check for existing pdf file and remove it
NSError *pdfDeleteError;
if ([[NSFileManager defaultManager] fileExistsAtPath:outputPDFfileName]){
//removing file
if (![[NSFileManager defaultManager] removeItemAtPath:outputPDFfileName error:&pdfDeleteError]){
NSString * errorMessage = [NSString stringWithFormat:#"wk %d Could not remove old pdf files. Error:%#",j, pdfDeleteError];
NSLog(#"%#",errorMessage);
}
}
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:htmlFileUrl pathForPDF:[outputPDFfileName stringByExpandingTildeInPath] pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:#"HTMLtoPDF did succeed (%# / %#)", htmlToPDF, htmlToPDF.PDFpath];
NSLog(#"%#",result);
self.resultLabel.text = result;
} errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:#"HTMLtoPDF did fail (%#)", htmlToPDF];
NSLog(#"%#",result);
self.resultLabel.text = result;
}];
}
However, it crashes with
Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
Link to github:
https://github.com/iclems/iOS-htmltopdf
However, if I replace the for loop with a button pressed (trigger this function once per second) the app doesn't crash.
I think your for loop crashing is because you are using block within the for loop
So what happens here is that the another iteration of the calls the block before it completes the previous block call
so here what you can do that you can use dispatch_group feature of ios to call each iteration call on different thread instead of calling sequentially
so to achieve this you can create one method with block parametes and call the block in that method some thing like this,
- (void)blockTask:(NSString*)strPath
{
dispatch_group_enter(serviceGroup);
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:htmlFileUrl pathForPDF:[outputPDFfileName stringByExpandingTildeInPath] pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:#"HTMLtoPDF did succeed (%# / %#)", htmlToPDF, htmlToPDF.PDFpath];
NSLog(#"%#",result);
self.resultLabel.text = result;
dispatch_group_leave(serviceGroup);
} errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:#"HTMLtoPDF did fail (%#)", htmlToPDF];
NSLog(#"%#",result);
self.resultLabel.text = result;
dispatch_group_leave(serviceGroup);
}];
}
Note : This just a psuedo code may contains errors,
For dispatch_group tutorial check here

Copying a realm-file seems to cause realm Migration-block call - why?

After copying a .realm-file from folder-location1 to folder-location2 (and also changing its name from location1.realm to location2.realm using NSFileManager) - it seems that after doing so, the first call to this new file causes a migration-block call! (i.e. setSchemaVersion). I wonder WHY ???
Prior calls to the "location1/location1.realm" File did not cause a migration-block call - however calls to "location2/location2.realm" do - and the files are identical in structure (at least in Realm-Browser there is no obvious difference) !!
Here is my code :
ApplicatonSuppPathHandler *ApplicationSupportPathHandler = [[ApplicatonSuppPathHandler alloc] init];
// creation of location where this directory shall be placed on the iPhone
// typically /library/Application Support/<bundleID_name>/RLMGeneralDatabasesFolderName/...
// = name of directory that the .realm-File finally should be placed in
NSString *RLMLocation1DirectoryName = folderName;
// if it does not exist already, create the RLMLocation_xyz-directory (.../library/Application Support/<bundleID_name>/RLMDatabasesFolderName)
if([ApplicationSupportPathHandler getURLToApplicationDirectoryWithSubDirectory:RLMLocation1DirectoryName] == nil) {
[ApplicationSupportPathHandler createSubDirectoryAtLocationToApplicationDirectory:RLMLocation1DirectoryName];
}
// get the name of entire directory just created
NSURL *RLMLocation1Directory = [ApplicationSupportPathHandler getURLToApplicationDirectoryWithSubDirectory:RLMLocation1DirectoryName];
// name of entire path-name (including filename !! ...needed for copy function below...)
NSString *RLMLocation1Path = [[RLMLocation1Directory path] stringByAppendingPathComponent:fileName];
// HERE IS WHERE THE MIGRATION BLOCK IS CALLED - WHY ?????
// *******************************************************
RLMRealm *realm_Location1 = [RLMRealm realmWithPath:RLMLocation1Path]; // pointing to realm file at path
// the rest does work after the migration-block call...
[realm_Location1 beginWriteTransaction];
[realm_Location1 deleteAllObjects];
[realm_Location1 addObject:RLMTopoRes];
[realm_Location1 commitWriteTransaction];
Below is the implementation of the used ApplicationSuppPathHandler class-methods:
#implementation ApplicatonSuppPathHandler
- (NSURL*)getURLToApplicationDirectoryWithSubDirectory:(NSString*)SubDirectoryName {
NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager*fm = [NSFileManager defaultManager];
NSURL* dirPath = nil;
// Find the application support directory in the home directory.
NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
if ([appSupportDir count] > 0)
{
// Append the bundle ID and the location-Foldername to the URL for the Application Support directory
dirPath = [[[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:appBundleID] URLByAppendingPathComponent:SubDirectoryName];
BOOL isDir;
BOOL exists = [fm fileExistsAtPath:[dirPath path] isDirectory:&isDir];
if (exists) {
/* file exists */
if (isDir) {
/* path exists */
return dirPath;
}
else {
NSLog(#"Directory does not exist");
return nil;
}
}
else {
/* file does not exist */
return nil;
}
}
return dirPath;
}
- (void)createSubDirectoryAtLocationToApplicationDirectory:(NSString*)SubDirectoryName {
NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager*fm = [NSFileManager defaultManager];
NSURL* dirPath = nil;
// Find the application support directory in the home directory.
NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
if ([appSupportDir count] > 0)
{
// Append the bundle ID and the location-Foldername to the URL for the Application Support directory
dirPath = [[[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:appBundleID] URLByAppendingPathComponent:SubDirectoryName];
// If the directory does not exist, this method creates it.
// This method call works in OS X 10.7 and later only.
NSError* theError = nil;
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError]) {
// Handle the error.
NSLog(#"%#", theError.localizedDescription);
}
else {
// Mark the directory as excluded from iCloud backups
if (![dirPath setResourceValue:#YES
forKey:NSURLIsExcludedFromBackupKey
error:&theError]) {
NSLog(#"Error excluding %# from iCloud backup %#", [dirPath lastPathComponent], theError.localizedDescription);
}
else {
// NSLog(#"Location Directory excluded from iClud backups");
}
}
}
}
There was previously a bug in Realm where new realm files would have their schema version set to 0 instead of the current schema version, which would trigger a migration in your case.
A fix for this was pushed to the master branch of Realm last week: https://github.com/realm/realm-cocoa/pull/1142
Building Realm from master should address the issue you're having. Realm v0.88.0 will be released shortly with this fix.
...hhm - seems that another method messed up !
The below code shows this method that loads data from a realm-file into a realm-wrapper-object.
Coming back to the original problem (location2/location2.realm file creating migraton-block):
Unfortunately, I was not aware that calling this "loadData_..."-method needed to be called with caution ! If it is called twice - once to location1/location1.realm and then a second time (to location2/location2.realm) - that is when things get messed up !
I tried to create a "wrapper" that loads and saves Realm-objects. But it seems more difficult with Realm than originally expected. Thanks for any comment on this !!
- (void) loadData_at_TopoNr_from_LocationRLM :(NSNumber *)TopoNr :(NSString *)folderName :(NSString *)fileName {
// realm-object calling "get_TopoResultRLM_FilePath" must be of same object-type, otherwise block-migration call !
RLMRealm *realm = [RLMRealm realmWithPath:[self get_TopoResultRLM_FilePath :folderName :fileName]];
RLMResults *resTopoResult = [RLMTopoResult allObjectsInRealm:realm];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:#"TopoNrRLM == %d", [TopoNr intValue]];
RLMResults *resultTopoResult = [resTopoResult objectsWithPredicate:predicate1];
if ([resultTopoResult count] <= 1) {
if ([resultTopoResult count] == 1) {
// found one object
// data loading
self.TopoNrRLM = [resultTopoResult.firstObject TopoNrRLM];
self.nameAnamneserRLM = [resultTopoResult.firstObject nameAnamneserRLM];
self.anamneseDateRLM = [resultTopoResult.firstObject anamneseDateRLM];
self.NumberOfCriteriaRLM = [resultTopoResult.firstObject NumberOfCriteriaRLM];
self.BestMatchMethodRLM = [resultTopoResult.firstObject BestMatchMethodRLM];
self.RealmFrameworkVersionRLM = [resultTopoResult.firstObject RealmFrameworkVersionRLM];
self.BoundaryConditionVerionRLM = [resultTopoResult.firstObject BoundaryConditionVerionRLM];
self.CriteriaRLM = [resultTopoResult.firstObject CriteriaRLM];
self.imageNameRLM = [resultTopoResult.firstObject imageNameRLM];
self.imageDataRLM = [resultTopoResult.firstObject imageDataRLM];
}
else { ....
Here is the property definition of the wrapper-object-class :
// GUIData-RLM
#property (nonatomic) RLMGUIData *GUIDataRLM;
// Location-RLM
#property (nonatomic) RLMTopoResult *LocationRLM;
Here is the object creation and call of that loadData_at...-method :
RLMTopoResult *LocationRealm = [[RLMTopoResult alloc] init];
[self setLocationRLM:LocationRealm];
[LocationRealm loadData_at_TopoNr_from_LocationRLM :[NSNumber numberWithInt:[GUIDataRealm TopoNrRLM]] :[GUIDataRealm locationFolderNameRLM] :[NSString stringWithFormat:#"%#%s", [GUIDataRealm locationFolderNameRLM], ".realm"]];

Import .ics File and show in Calendar or UITableView

I retrieve an .ics file from a certain url. I'd like to present the information of this file in a calendar and/or list view in my own app. I had a look at iCal4Objc("https://github.com/cybergarage/iCal4ObjC") and parsed the information like this:
-(NSMutableArray *)getPlanFromURL:(NSURL *)url {
NSMutableArray *planEntries = [[NSMutableArray alloc]init];
NSString *storePath = [self loadICSAndReturnPathFromURL:url];
CGICalendar *parserCalendar = [[CGICalendar alloc]initWithPath:storePath];
for(CGICalendarObject *planObject in [parserCalendar objects]) {
for(CGICalendarComponent *component in [planObject components]) {
for (CGICalendarProperty *icalProp in [component properties]) {
NSString *icalPropName = [icalProp name];
NSLog(#"%#",icalPropName);
if([icalPropName isEqualToString:SUMMARY]) {
[self.summaryArray addObject:[icalProp value]];
}
else if([icalPropName isEqualToString:LOCATION]) {
[self.locationArray addObject:[icalProp value]];
}
else if([icalPropName isEqualToString:CATEGORIES]) {
[self.categoryArray addObject:[icalProp value]];
}
else if([icalPropName isEqualToString:DTSTART]) {
[self.startArray addObject:[icalProp dateValue]];
}
else if([icalPropName isEqualToString:DTEND]) {
[self.endArray addObject:[icalProp dateValue]];
}
}
}
}
for(int i = 0;i<[self.summaryArray count];i++) {
DECalEntry *entry = [[DECalEntry alloc]init];
entry.summary = [self.summaryArray objectAtIndex:i];
entry.roomInformation = [self.locationArray objectAtIndex:i];
entry.category = [self.categoryArray objectAtIndex:i];
entry.startDate = [self.startArray objectAtIndex:i];
entry.endDate = [self.endArray objectAtIndex:i];
if ([entry.category isEqualToString:#"Prüfung"]) {
entry.isExam = true;
}
else entry.isExam = false;
[planEntries addObject:entry];
}
return planEntries;
}
-(NSString *)loadICSAndReturnPathFromURL:(NSURL *)url {
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *storePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"planData.ics"];
[data writeToFile:storePath atomically:YES];
return storePath;
}
NSLog(#"Error: %#",[error localizedDescription]);
return nil;
}
Since this is not very clean and it would be a pain to also implement UITableView and a calendar view to illustrate the parsed data i asked me whether there exists a framework that one of you knows which already can handle .ics files and shows them accordingly.
If you have an idea how to solve this issue less complicated and/or with less effort i would be really grateful.
Also have a look at my comment. At the moment the rrule property is not considered at all. But this is very important since it shows me if a event is repeated, until it is repeated and so on...
Nevermind i got it working myself by parsing the rrule property like i did it with the other properties and constructed a method which creates the right amount of objects i need by following the information that this property contains. Well i just think this was the only way because apparently the is no framework for importing and parsing .ics files. When i finish my project i might give it a shot for people who might face this one day.
To my knowledge there is no framework or control provided by Apple that displays .ics files, but once you construct an EKEvent, there is:
https://developer.apple.com/library/ios/documentation/EventKitUI/Reference/EKEventEditViewControllerClassRef/Reference/Reference.html#//apple_ref/doc/uid/TP40009571
Specifically, you want to take a look at EventKitUI.framework.

iOS exec function in background

I am new to multithreading and was wondering how I could run this function in the background? The function simply returns a NSURL that is used for XML parsing and is called from another function. Or is it even worth it to run in the background since the function that calls it does not continue until this function returns its NSURL. Basically, I am just trying to figure out how to speed this up because it is taking a little time to finish!
+ (NSURL *)parserURL {
NSURL *theURL = [NSURL URLWithString:#"http://www.wccca.com/PITS/"];
NSData *data = [[NSData alloc] initWithContentsOfURL:theURL];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
NSArray *elements = [xpathParser searchWithXPathQuery:#"//input[#id='hidXMLID']//#value"];
if (elements.count >= 1) {
TFHppleElement *element = [elements objectAtIndex:0];
TFHppleElement *child = [element.children objectAtIndex:0];
NSString *idValue = [child content];
NSString *stg = [NSString stringWithFormat:#"http://www.wccca.com/PITS/xml/fire_data_%#.xml", idValue];
NSURL *url = [NSURL URLWithString:stg];
return url;
}
return nil;
}
The main issue with your code is that you are using a blocking operation to get the data from the website. You definitely want to execute this in the background thread. However, I would recommend you to have a look at networking frameworks that help you do these kinds of operations very easily, i.e., AFNetworking,
In any case, the strategy that I would follow to multithread that operation, or a similar one is the following:
It breaks down to dispatching it with GDC, and then executing a receiving completion block back in the main thread with the results.
Here is the code:
Description
First start by declaring your function to receive a block. The block will be executed in the end, once you've finished retrieving and parsing the data. The next thing the code does it asking GDC to execute a block of code in a background queue. When it is done, we ask the code to execute the completion block that was provided as parameter of the function in the main thread, supplying the parsed string to it.
+(void) parserURL:(NSURL *) theURL completion:(void (^) (NSURL *finalURL))completionBlock{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [[NSData alloc] initWithContentsOfURL:theURL];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
NSArray *elements = [xpathParser searchWithXPathQuery:#"//input[#id='hidXMLID']//#value"];
NSURL *url;
if (elements.count >= 1) {
TFHppleElement *element = [elements objectAtIndex:0];
TFHppleElement *child = [element.children objectAtIndex:0];
NSString *idValue = [child content];
NSString *stg = [NSString stringWithFormat:#"http://www.wccca.com/PITS/xml/fire_data_%#.xml", idValue];
url = [NSURL URLWithString:stg];
}else{
url = nil;
}
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(url);
});
});
}
You call the method the following way:
[URLParser parserURL:[NSURL URLWithString:#"http://www.wccca.com/PITS/"] completion:^(NSURL *finalURL) {
NSLog(#"Parsed string %#", [finalURL absoluteString]);
}];

iOS: Custom class import

I moved some code that will be used multiple times into a class.
I'm not getting errors, but I'm also not getting results. It seems to skip over my class completely.
Ideally, this class is supposed to do NSURL conns and XMLParser stuff to chew up the data feed from our hosting API. I already have this working but wanted to congeal and somewhat normalize/centralize some of the main logic of my code.
The one function 'bdCheckIfFileExistsAndisValid' is supposed to take a string but return BOOL and it isn't being called at all.
Neither is 'bdParsePlaylistXML' that is supposed to take a string and return an array.
I put breakpoints everywhere in my class and none are hit.
I'm new so I'm not sure if I did everything right. Here's some code, thanks in advance.
--------------------CUSTOM CLASS:(.h)
#interface bdXMLParser : NSObject {
NSMutableArray *playlist;
//Playlist XML info
BOOL recordTrackName;
BOOL recordTrackDescription;
BOOL recordTrackThumbnailAbsoluteLocation;
BOOL recordTrackURL;
NSString *TrackName;
NSString *TrackDescription;
NSString *TrackThumbnailAbsoluteLocation;
NSString *TrackURL;
}
-(NSMutableArray*) bdParsePlaylistXML:(NSString *) playlistXMLFileName;
-(BOOL) bdCheckIfFileExistsAndisValid:(NSString *) localFileName;
----------------CUSTOM CLASS (.m):
#import "bdXMLParser.h"
#implementation bdXMLParser
{
NSMutableData *webData;
NSMutableArray *playlist;
NSXMLParser *xmlParserPlaylist;
}
-(NSString*) bdDocumentsDirectory{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return documentsPath;
}
-(int) bdCheckFileCreationDate:(NSString *) fileName {
//get XML file path
NSString *localFilePath = [[self bdDocumentsDirectory] stringByAppendingPathComponent:fileName];
//local file check
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSDictionary* attrs = [filemgr attributesOfItemAtPath:localFilePath error:nil];
NSDate *fileCreationDate = [attrs objectForKey: NSFileCreationDate];
NSDate *rightNow = [NSDate date];
NSTimeInterval lastDiff = [fileCreationDate timeIntervalSinceNow];
int lastDiffINT = round(lastDiff);
NSLog(#"NSFileCreationDate:%#",fileCreationDate);
NSLog(#"CurrentDate:%#",rightNow);
NSLog(#"lastDiff:%f",lastDiff);
return lastDiffINT;
}
-(BOOL) bdCheckIfFileExistsAndisValid:(NSString *) fileName {
//local file check
NSString* foofile = [[self bdDocumentsDirectory] stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
if ((fileExists == YES) && ([self bdCheckFileCreationDate:foofile] > -86400))//(24 hrs = 86400 seconds)
return YES;
else
return NO;
}
HERE's THE VIEW WHERE I'M TRYING TO USE IT:(menu.h)
#import "bdXMLParser.h"
#interface MenuScreenViewController : UIViewController <NSXMLParserDelegate>
- (IBAction)btnPlayerPlayPause:(id)sender;
(menu.m)
- (IBAction)btnPlayerPlayPause:(id)sender {
//if array exists, don't reload xml, dont reparse xml, just go to the view
if (playlist.count == 0){
//Playlist!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//========================================================================
//1st: check to see if we have a local cached xml data
//if we do, check if it is <24hr old and if so load it
//if not, go get it with connection and overwrite/store it
//init blogs NSMutableArray
playlist = [[NSMutableArray alloc] init];
//local file check
bdXMLParser *myParser;
BOOL fileExistsAndValid = NO;
=HERE!==fileExistsAndValid = [myParser bdCheckIfFileExistsAndisValid:PlaylistName];
//1st
if (fileExistsAndValid)//(<24 hrs old)
{
NSLog (#"File fileExistsAndValid");
=AND HERE!!=playlist = [myParser bdParsePlaylistXML:PlaylistName];
NSLog(#"playlist:%u", playlist.count);
//load first track
[self LoadTrack:0];
}
else{
NSLog (#"File doesn't exist");
//call refresh function
//[self refreshAlbumPhotoXML];
[myParser bdRefreshPlaylistXML];
}
}
}
you forgot initing the class
bdXMLParser *myParser= [[bdXMLParster alloc]init];

Resources