Search Results

Search found 1559 results on 63 pages for 'nslog'.

Page 6/63 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • UIPageViewController blanking page

    - by CrazyEoin
    I've been trying to use the UIPageViewController to display 3 different nibs for a few days on and off now and have almost got it working. I still have one weird bug that I cant figure out. Basically the app starts, I can scroll between the 3 pages one after another with out any problems, eg: Page1-Page2-Page3 and then back to the start: Page3-Page2-Page1. No Problems. The issue is that if I scroll, for example from Page3-Page2, then BACK to Page3, Page3 Dissappears when it snaps into place. If I scroll to where a forth page would be, then I get Page3. Here is the code relevant to the UIPageViewController, the nibs and the delegate methods for the UIPageViewController: - (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; self.pageViewController.delegate = self; [[self.pageViewController view] setFrame:[[self view] bounds]]; indexTest = 0; Page1 *p1 = [[Page1 alloc]initWithNibName:@"Page1" bundle:nil]; p1.view.tag = 1; Page2 *p2 = [[Page2 alloc]initWithNibName:@"Page2" bundle:nil]; p2.view.tag = 2; Page3 *p3 = [[Page3 alloc]initWithNibName:@"Page3" bundle:nil]; p3.view.tag = 3; NSArray *arr = [[NSArray alloc] initWithObjects:p1,nil]; viewControllers = [[NSMutableArray alloc] initWithObjects:p1,p2,p3, nil]; [self.pageViewController setViewControllers:arr direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; self.pageViewController.dataSource = self; [self addChildViewController:self.pageViewController]; [[self view] addSubview:[self.pageViewController view]]; [self.pageViewController didMoveToParentViewController:self]; self.view.gestureRecognizers = self.pageViewController.gestureRecognizers; } #pragma mark - page view controller stuff - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { if (indexTest > 0) { switch (indexTest) { case 1:{ NSLog(@"NO page is BEFORE current page"); break; } case 2:{ NSLog(@"Page BEFORE is Page: %@", [NSString stringWithFormat:@"%@",[viewControllers objectAtIndex:0] ] ); indexTest--; return [viewControllers objectAtIndex:0]; break; } default:{ NSLog(@"PROBLEM in viewBEFORE, indexTest = %d!!!!", indexTest); break; } } } return nil; } - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { if (indexTest < NUM_OF_PAGES) { switch (indexTest) { case 0:{ NSLog(@"Page AFTER is Page: %@", [NSString stringWithFormat:@"%@",[viewControllers objectAtIndex:1] ] ); indexTest++; return [viewControllers objectAtIndex:1]; break; } case 1:{ NSLog(@"Page AFTER is Page: %@", [NSString stringWithFormat:@"%@",[viewControllers objectAtIndex:2] ] ); indexTest++; return [viewControllers objectAtIndex:2]; break; } case 2:{ NSLog(@"No pages AFTER this current page %d", indexTest); break; } default:{ NSLog(@"PROBLEM in viewAFTER, indexTest = %d!!!!", indexTest); break; } } } return nil; } Finally the page index dots code #pragma mark - dot controller - (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController { // The number of items reflected in the page indicator. return NUM_OF_PAGES; } - (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController { // The selected item reflected in the page indicator. return 0; } Any and all help is much appreciated, I think I'm just doing something silly that I cant see as I'm so close to it fully working. If anythings not clear or I haven't give enough information please let me know and I'll answer it as best as I can. Thanks

    Read the article

  • Why doesen't the number 2 work in this for-loop?

    - by Emil
    Hello. I have a function that runs trough each element in an array. It's hard to explain, so I'll just paste in the code here: NSLog(@"%@", arraySub); for (NSString *string in arrayFav){ int favoriteLoop = [string intValue] + favCount; NSLog(@"%d", favoriteLoop); id arrayFavObject = [array objectAtIndex:favoriteLoop]; [arrayFavObject retain]; [array removeObjectAtIndex:favoriteLoop]; [array insertObject:arrayFavObject atIndex:0]; [arrayFavObject release]; id arraySubFavObject = [arraySub objectAtIndex:favoriteLoop]; [arraySubFavObject retain]; [arraySub removeObjectAtIndex:favoriteLoop]; [arraySub insertObject:arraySubFavObject atIndex:0]; [arraySubFavObject release]; id arrayLengthFavObject = [arrayLength objectAtIndex:favoriteLoop]; [arrayLengthFavObject retain]; [arrayLength removeObjectAtIndex:favoriteLoop]; [arrayLength insertObject:arrayLengthFavObject atIndex:0]; [arrayLengthFavObject release]; } NSLog(@"%@", arraySub); The array arrayFav contains these strings: "3", "8", "2", "10", "40". Array array contains 92 strings with a name. Array arraySub contains numbers 0 to 91, representing a filename with a title from the array array. Array arrayLength contains 92 strings representing the size of each file from array arraySub. Now, the first NSLog shows, as expected, the numbers 0 to 91. The NSLog-s in the loop shows the numbers 3, 8, 2, 10, 40, also as expected. But here's the odd part: the last NSLog shows these numbers: 40, 10, 0, 8, 3, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91 that is 40, 10, 0, 8, 3, and so on. It was not supposed to be a zero in there, it was supposed to be a 2.. Do you have any idea at why this is happening or a way to fix it? Thank you.

    Read the article

  • can I store an id value in array of float type ?

    - by srikanth rongali
    I used, for(id value in values) to get the value from an NSArray. Now I want to store it in 2 dimensional float array[][]. When I try to assign the values to array it is giving error:incompatible types in assignment. I tried to cast the value but I got error: pointer value used where a floating point value was expected. I need to store the values in an 2 dimensional array . How can I make it ? Thank You. @implementation fromFileRead1 NSString *fileNameString; int numberOfEnemies, numberOfValues; -(id)init { if( (self = [super init]) ) { NSString *path = @"/Users/sridhar/Desktop/Projects/exampleOnFile2/enemyDetals.txt"; NSString *contentsOfFile = [[NSString alloc] initWithContentsOfFile:path]; NSArray *lines = [contentsOfFile componentsSeparatedByString:@"\n"]; numberOfEnemies = [lines count]; NSLog(@"The number of Lines: %d", numberOfEnemies); for (id line in lines) { NSLog(@"Line %@", line ); NSString *string1 = line; NSArray *split1 = [string1 componentsSeparatedByString:@","]; numberOfValues = [split1 count]; NSLog(@"The number of values in Row: %d", numberOfValues); for (id value in split1) { NSLog(@"value %@", value); float value1; value1 = [split1 objectAtIndex:2]); NSLog(@"VAlue of Value1 at index 2: %f", value1 ); } } } return self; } @end In enemyDetal.txt I have 1,3,3 2,3,2.8 10,2,1.6

    Read the article

  • dismissing uiwebview

    - by chimgrrl
    Ok, I really spend 2 days on this and it has gotten me stumped. From my main UIViewController I called a WebViewController which is a UIViewController with a UIWebView inside: UOLCategoriesWebViewController *ucwvcontroller = [[UOLCategoriesWebViewController alloc] initWithNibName:@"UOLCategoriesWebViewController" bundle:nil]; [self presentModalViewController:ucwvcontroller animated:YES]; [ucwvcontroller release]; Inside the UOLCategoriesWebViewController I've call the delegate method shouldStartLoadWithRequest where when the user clicks on a particular type of link it parses out the params and return back to the main UIViewController (or at least that's what I want it to do): - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { BOOL continueOrExit = YES; NSURL *url = request.URL; NSString *urlString = [url relativeString]; NSString *urlParams = [url query]; NSArray *urlParamArr = [urlParams componentsSeparatedByString:@"&"]; NSLog(@"the url is: %@",urlString); //NSLog(@"the params are: %@,%@",[urlParamArr objectAtIndex:0],[urlParamArr objectAtIndex:1]); //BOOL endTrain1 = [[urlParamArr objectAtIndex:1] hasPrefix:@"subCatValue"]; //BOOL endTrain2 = ([urlParamArr objectAtIndex:1 //NSLog(@"Number of elements: %@",[urlParamArr count]); if (navigationType == UIWebViewNavigationTypeLinkClicked) { //NSLog(@"Enter into His glory"); if ([urlString hasSuffix:@"categories_list.php"]) { //NSLog(@"2nd Heaven"); continueOrExit = YES; }else if ([[urlParamArr objectAtIndex:1] hasPrefix:@"subCatValue"]) { continueOrExit = NO; NSLog(@"end of the train"); NSArray *firstParamStringArr = [[urlParamArr objectAtIndex:0] componentsSeparatedByString:@"="]; NSArray *secondParamStringArr = [[urlParamArr objectAtIndex:1] componentsSeparatedByString:@"="]; NSString *catSelected = [firstParamStringArr objectAtIndex:1]; NSString *subCatSelected = [secondParamStringArr objectAtIndex:1]; //go back to native app [self goBackToMain:catSelected andSubCat:subCatSelected]; } } return continueOrExit; } Actually in the above function where I am calling the goBackToMain method I want it to call the delegate method and return to the mainviewcontroller. Unfortunately after executing that goBackToMain method it goes back to this method and continue to return continueOrExit. Is there anyway to make it truly exit without returning anything? I've tried putting in multiple returns to no avail. Or can I in the html page pass some javascript to directly call this method so that I don't have to go through this delegate method? Thanks for the help in advance!

    Read the article

  • Bulk update & occasional insert (coredata) - Too slow

    - by Andrew
    Update: Currently looking into NSSET's minusSet links: http://stackoverflow.com/questions/1475636/comparing-two-arrays Hi guys, Could benefit from your wisdom here.. I'm using Coredata in my app, on first launch I download a data file and insert over 500 objects (each with 60 attributes) - fast, no problem. Each subsequent launch I download an updated version of the file, from which I need to update all existing objects' attributes (except maybe 5 attributes) and create new ones for items which have been added to the downloaded file. So, first launch I get 500 objects.. say a week later my file now contains 507 items.. I create two arrays, one for existing and one for downloaded. NSArray *peopleArrayDownloaded = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeopleTemp]; NSArray *peopleArrayExisting = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeople]; If the count of each array is equal then I just do this: NSUInteger index = 0; if ([peopleArrayExisting count] == [peopleArrayDownloaded count]) { NSLog(@"Number of people downloaded is same as the number of people existing"); for (person *existingPerson in peopleArrayExisting) { person *tempPerson = [peopleArrayDownloaded objectAtIndex:index]; // NSLog(@"Updating id: %@ with id: %@",existingPerson.person_id,tempPerson.person_id); // I have 60 attributes which I to update on each object, is there a quicker way other than overwriting existing? index++; } } else { NSLog(@"Number of people downloaded is different to number of players existing"); So now comes the slow part. I end up using this (which is tooooo slow): NSLog(@"Need people added to the league"); for (person *tempPerson in peopeArrayDownloaded) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person_id = %@",tempPerson.person_id]; // NSLog(@"Searching for existing person, person_id: %@",existingPerson.person_id); NSArray *filteredArray = [peopleArrayExisting filteredArrayUsingPredicate:predicate]; if ([filteredArray count] == 0) { NSLog(@"Couldn't find an existing person in the downloaded file. Adding.."); person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"person" inManagedObjectContext:managedObjectContextPeople]; Is there a way to generate a new array of index items referring to the additional items in my downloaded file? Incidentally, on my tableViews I'm using NSFetchedResultsController so updating attributes will call [cell setNeedsDisplay]; .. about 60 times per cell, not a good thing and it can crash the app. Thanks for reading :)

    Read the article

  • sqlite 3 opening issue

    - by anonymous
    I'm getting my data ,with several similar methods, from sqlite3 file like in following code: -(NSMutableArray *) getCountersByID:(NSString *) championID{ NSMutableArray *arrayOfCounters; arrayOfCounters = [[NSMutableArray alloc] init]; @try { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *databasePath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"DatabaseCounters.sqlite"]; BOOL success = [fileManager fileExistsAtPath:databasePath]; if (!success) { NSLog(@"cannot connect to Database! at filepath %@",databasePath); } else{ NSLog (@"SUCCESS getCountersByID!!"); } if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK){ NSString *tempString = [NSString stringWithFormat:@"SELECT COUNTER_ID FROM COUNTERS WHERE CHAMPION_ID = %@",championID]; const char *sql = [tempString cStringUsingEncoding:NSASCIIStringEncoding]; sqlite3_stmt *sqlStatement; int ret = sqlite3_prepare(database, sql, -1, &sqlStatement, NULL); if (ret != SQLITE_OK) { NSLog(@"Error calling sqlite3_prepare: %d", ret); } if(sqlite3_prepare_v2(database, sql, -1, &sqlStatement, NULL) == SQLITE_OK){ while (sqlite3_step(sqlStatement)==SQLITE_ROW) { counterList *CounterList = [[counterList alloc]init]; CounterList.counterID = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)]; [arrayOfCounters addObject:CounterList]; } } else{ NSLog(@"problem with database prepare"); } sqlite3_finalize(sqlStatement); } else{ NSLog(@"problem with database openning %s",sqlite3_errmsg(database)); } } @catch (NSException *exception){ NSLog(@"An exception occured: %@", [exception reason]); } @finally{ sqlite3_close(database); return arrayOfCounters; } //end } then i'm getting access to data with this and other similar lines of code: myCounterList *MyCounterList = [[myCounterList alloc] init]; countersTempArray = [MyCounterList getCountersByID:"2"]; [countersArray addObject:[NSString stringWithFormat:@"%@",(((counterList *) [countersTempArray objectAtIndex:i]).counterID)]]; I'm getting a lot of data like image name and showing combination of them that depends on users input with such code: UIImage *tempImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_0.jpg",[countersArray objectAtIndex:0]]]; [championSelection setBackgroundImage:tempImage forState:UIControlStateNormal]; My problem: When i'm run my app for some time and get a lot of data it throws error: " problem with database openning unable to open database file - error = 24 (Too many open files)" My guess is that i'm opening my database every time when getCountersByID is called but not closing it. My question: Am i using right approach to open and close database that i use? Similar questions that have not helped me to solve this problem: unable to open database Sqlite Opening Error : Unable to open database UPDATE: I made assumption that error is showing up because i use this lines of code too much: NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *databasePath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"DatabaseCounters.sqlite"]; BOOL success = [fileManager fileExistsAtPath:databasePath]; and ending up with error 24. So i made them global but sqlite3_errmsg shows same err 24, but app runs much faster now I'll try to debug my app, see what happens

    Read the article

  • NSInvalidArgumentException – App terminates while i'm trying to copy a captured video to documents f

    - by ChrNis
    I'd like to try the wisdom of the crowds..because i'm frustrated right now. Thanks in advance. So here is my code: - (void)imagePickerController:(UIImagePickerController *)ipc didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSLog(@"info: %@",info); NSString *newFilename = [NSString stringWithFormat:@"%@/%@.mov", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"], [NSString stringWithFormat:@"%d", (long)[[NSDate date] timeIntervalSince1970]]]; NSLog(@"newFilename: %@",newFilename); NSFileManager *filemgr = [NSFileManager defaultManager]; NSError *err; if ([filemgr copyItemAtPath:[info objectForKey:@"UIImagePickerControllerMediaURL"] toPath:newFilename error:&err] == YES) NSLog (@"Move successful"); else NSLog (@"Move failed"); and this is the log: 2010-05-16 18:19:01.975 erlkoenig[7099:307] info: { UIImagePickerControllerMediaType = "public.movie"; UIImagePickerControllerMediaURL = "file://localhost/private/var/mobile/Applications/BE25F9B5-2D08-4B59-8B62-D04DF7BB7E5B/tmp/-Tmp-/capture-T0x108cb0.tmp.8M81HU/capturedvideo.MOV"; } newFilename: /var/mobile/Applications/BE25F9B5-2D08-4B59-8B62-D04DF7BB7E5B/Documents/1274026741.mov [NSURL fileSystemRepresentation]: unrecognized selector sent to instance 0x1c1f90 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL fileSystemRepresentation]: unrecognized selector sent to instance 0x1c1f90

    Read the article

  • NSMutableArray of Objects misbehaves ...

    - by iFloh
    I hope someone understands what happens to my NSMutableArray. I read records a, b, c, d from a database, load the fields into an object an add the object to an array. To do this I read the records into an instance of that object (tmpEvent) and add the Object to the target array (NSMutableArray myArray). the code looks like: for (condition) { tmpEvent.field1 = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)]; tmpEvent.field2 = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 1)]; tmpEvent.field3 = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 2)]; NSLog(@"myArray: adding %@", tmpEvent.field1); [myArray addObject:tmpEvent]; } The NSLog shows myArray: adding a myArray: adding b myArray: adding c myArray: adding d Subsequent I enumerate the array (this can be in the same or a different method): for (myObject *records in myArray) { NSLog(@"iEvents value %@", records.field1); } The NSLog now shows: myArray value d myArray value d myArray value d myArray value d a mystery .... ??? any thoughts?

    Read the article

  • NSDate compare is false?

    - by user1280535
    i compare 2 NSDates which are the same and i get false result. i cant show how i get this dates because its too long , but i can show what i do : NSLog(@"this date is:%@ , and date we check to equality is:%@",thisDate,dateToFind); if([thisDate isEqualToDate:dateToFind] ) { NSLog(@"equal date!"); // not printed! } the NSLog show me this : this date is:2012-09-13 14:23:54 +0000 , and date we check to equality is:2012-09-13 14:23:54 +0000 he doesnt print the NSLog . why ?

    Read the article

  • numberOfSectionsInTable isn't called when [arr count] is returned

    - by user315471
    When I try returning the count of my newsItems array it breaks my application. I used NSLog to find out what the value of the newsItems count was when I returned 1. Here is from NSLog 2010-04-13 07:48:40.656 RSS Feed[453:207] Values of num items 31 2010-04-13 07:48:40.656 RSS Feed[453:207] Number of items 31 Does anyone know why returning [newsItems count] would cause my application to break? - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSLog(@"Values of num items %d",[newsItems count]); NSInteger *length = (NSInteger *)[newsItems count]; NSLog(@"Number of items %d",length); return 1; //return [newsItems count]; //This keeps breaking it for some reason }

    Read the article

  • Simple iOS Get Request Not Pulling in Data

    - by user2793987
    I have a very simple get request that doesn't return data on my script. The script is fine when viewed in the web browser but the app does not pull in the data. Any other script works with this code in the app. I'm unsure of what to do because there shouldn't be a reason for this to not work. Please let me know if you need more information. Here's the script: https://shipstudent.com/complaint_desk/similarPosts.php?username=noah //retrieve saved username from user defaults (it's noah) NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults]; savedUser = [eUser objectForKey:@"user"]; NSLog(@"%@",savedUser); in ViewDidLoad: NSString *categoryParam = [NSString stringWithFormat:@"https://shipstudent.com/complaint_desk/similarPosts.php?username=%@", savedUser]; NSURL *url = [NSURL URLWithString:categoryParam]; NSMutableURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection==nil) { NSLog(@"Invalid request"); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { postData = [[NSMutableData alloc]init]; NSLog(@"Response received"); } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [postData appendData:data]; NSLog(@"Data received"); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; similarPosts = [NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:nil]; [postsTbl reloadData]; for (id postObject in similarPosts) { NSLog(@"Relatable Post: %@",postObject); } }

    Read the article

  • NSInvalidArgumentException accessing NSMutableArray in a UITableView

    - by kashar28
    Hello, I am a noob in iPhone programming so kindly guide me. I have 5 buttons in a custom UITableViewCell. Following is the code to determine which button was pressed. In ProductTableCustomCell.m -(IBAction) getRating:(id) sender { ProductTableView *ptv = (ProductTableView *)self.superview; if((UIButton *) sender == box1) { [ptv.totalComments addObject:@"BOX2"]; } else if((UIButton *) sender == box2){ NSLog(@"Box2"); [ptv.totalComments addObject:@"BOX2"]; NSLog(@"Am I here?"); }else if((UIButton *) sender == box3){ NSLog(@"Box3"); [ptv.totalComments addObject:@"BOX3"]; }else if((UIButton *) sender == box4){ NSLog(@"Box4"); [ptv.totalComments addObject:@"BOX4"]; }else if((UIButton *) sender == box5){ NSLog(@"Box5"); [ptv.totalComments addObject:@"BOX5"]; } } Here totalComments is a NSMutableArray in ProductTableView which is a UITableView. If for example I click button2, then I get the following error: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[UITableView totalComments]: unrecognized selector sent to instance 0x4036e00'** I don't understand the problem. I have double checked the IBOutlets and IBActions as well. Everything seems proper. I think the problem is in the superview.Any help would be appreciated.

    Read the article

  • Migrating Core Data to new UIManagedDocument in iOS 5

    - by samerpaul
    I have an app that has been on the store since iOS 3.1, so there is a large install base out there that still uses Core Data loaded up in my AppDelegate. In the most recent set of updates, I raised the minimum version to 4.3 but still kept the same way of loading the data. Recently, I decided it's time to make the minimum version 5.1 (especially with 6 around the corner), so I wanted to start using the new fancy UIManagedDocument way of using Core Data. The issue with this though is that the old database file is still sitting in the iOS app, so there is no migrating to the new document. You have to basically subclass UIManagedDocument with a new model class, and override a couple of methods to do it for you. Here's a tutorial on what I did for my app TimeTag.  Step One: Add a new class file in Xcode and subclass "UIManagedDocument" Go ahead and also add a method to get the managedObjectModel out of this class. It should look like:   @interface TimeTagModel : UIManagedDocument   - (NSManagedObjectModel *)managedObjectModel;   @end   Step two: Writing the methods in the implementation file (.m) I first added a shortcut method for the applicationsDocumentDirectory, which returns the URL of the app directory.  - (NSURL *)applicationDocumentsDirectory {     return [[[NSFileManagerdefaultManager] URLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask] lastObject]; }   The next step was to pull the managedObjectModel file itself (.momd file). In my project, it's called "minimalTime". - (NSManagedObjectModel *)managedObjectModel {     NSString *path = [[NSBundlemainBundle] pathForResource:@"minimalTime"ofType:@"momd"];     NSURL *momURL = [NSURL fileURLWithPath:path];     NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];          return managedObjectModel; }   After that, I need to check for a legacy installation and migrate it to the new UIManagedDocument file instead. This is the overridden method: - (BOOL)configurePersistentStoreCoordinatorForURL:(NSURL *)storeURL ofType:(NSString *)fileType modelConfiguration:(NSString *)configuration storeOptions:(NSDictionary *)storeOptions error:(NSError **)error {     // If legacy store exists, copy it to the new location     NSURL *legacyPersistentStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"minimalTime.sqlite"];          NSFileManager* fileManager = [NSFileManagerdefaultManager];     if ([fileManager fileExistsAtPath:legacyPersistentStoreURL.path])     {         NSLog(@"Old db exists");         NSError* thisError = nil;         [fileManager replaceItemAtURL:storeURL withItemAtURL:legacyPersistentStoreURL backupItemName:niloptions:NSFileManagerItemReplacementUsingNewMetadataOnlyresultingItemURL:nilerror:&thisError];     }          return [superconfigurePersistentStoreCoordinatorForURL:storeURL ofType:fileType modelConfiguration:configuration storeOptions:storeOptions error:error]; }   Basically what's happening above is that it checks for the minimalTime.sqlite file inside the app's bundle on the iOS device.  If the file exists, it tells you inside the console, and then tells the fileManager to replace the storeURL (inside the method parameter) with the legacy URL. This basically gives your app access to all the existing data the user has generated (otherwise they would load into a blank app, which would be disastrous). It returns a YES if successful (by calling it's [super] method). Final step: Actually load this database Due to how my app works, I actually have to load the database at launch (instead of shortly after, which would be ideal). I call a method called loadDatabase, which looks like this: -(void)loadDatabase {     static dispatch_once_t onceToken;          // Only do this once!     dispatch_once(&onceToken, ^{         // Get the URL         // The minimalTimeDB name is just something I call it         NSURL *url = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@"minimalTimeDB"];         // Init the TimeTagModel (our custom class we wrote above) with the URL         self.timeTagDB = [[TimeTagModel alloc] initWithFileURL:url];           // Setup the undo manager if it's nil         if (self.timeTagDB.undoManager == nil){             NSUndoManager *undoManager = [[NSUndoManager  alloc] init];             [self.timeTagDB setUndoManager:undoManager];         }                  // You have to actually check to see if it exists already (for some reason you can't just call "open it, and if it's not there, create it")         if ([[NSFileManagerdefaultManager] fileExistsAtPath:[url path]]) {             // If it does exist, try to open it, and if it doesn't open, let the user (or at least you) know!             [self.timeTagDB openWithCompletionHandler:^(BOOL success){                 if (!success) {                     // Handle the error.                     NSLog(@"Error opening up the database");                 }                 else{                     NSLog(@"Opened the file--it already existed");                     [self refreshData];                 }             }];         }         else {             // If it doesn't exist, you need to attempt to create it             [self.timeTagDBsaveToURL:url forSaveOperation:UIDocumentSaveForCreatingcompletionHandler:^(BOOL success){                 if (!success) {                     // Handle the error.                     NSLog(@"Error opening up the database");                 }                 else{                     NSLog(@"Created the file--it did not exist");                     [self refreshData];                 }             }];         }     }); }   If you're curious what refreshData looks like, it sends out a NSNotification that the database has been loaded: -(void)refreshData {     NSNotification* refreshNotification = [NSNotificationnotificationWithName:kNotificationCenterRefreshAllDatabaseData object:self.timeTagDB.managedObjectContext  userInfo:nil];     [[NSNotificationCenter defaultCenter] postNotification:refreshNotification];     }   The kNotificationCenterRefreshAllDatabaseData is just a constant I have defined elsewhere that keeps track of all the NSNotification names I use. I pass the managedObjectContext of the newly created file so that my view controllers can have access to it, and start passing it around to one another. The reason we do this as a Notification is because this is being run in the background, so we can't know exactly when it finishes. Make sure you design your app for this! Have some kind of loading indicator, or make sure your user can't attempt to create a record before the database actually exists, because it will crash the app.

    Read the article

  • How to use Devicemotion/Gyroscope to move a dot from center to 8 directions of iphone screen

    - by iSeeker
    I am trying to move a dot at center to 8 directions of iphone screen using Devicemotion such that it moves faster when tilted at a faster rate. Rough sketch is below: I could find a similar implementation in an app called Gyrododge in appstore, i cant figure out how to make it work... Update: This is what i have done so far, but the response is not smooth, and is very jittery.. xdiff and ydiff are the change of device attitude in x and y directions, derived from quatenion implementation. if (currDeviceMotion.rotationRate.x < -2) { NSLog(@"To Top"); if (195+800*ydiff >=193 && 195+800*ydiff <= 197) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (195+800*ydiff >=390 ) { [self.pitchDot setFrame:CGRectMake(150, 390, 20, 20)]; }else if (195+800*ydiff <= 0){ [self.pitchDot setFrame:CGRectMake(150, 0, 20, 20)]; }else if(195+800*ydiff < 194){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; }else if(195+800*ydiff > 196){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 2){ NSLog(@"To Bottom"); if (195+800*ydiff >=193 && 195+800*ydiff <= 197) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (195+800*ydiff >=390 ) { [self.pitchDot setFrame:CGRectMake(150, 390, 20, 20)]; }else if (195+800*ydiff <= 0){ [self.pitchDot setFrame:CGRectMake(150, 0, 20, 20)]; }else if(195+800*ydiff < 194){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; }else if(195+800*ydiff > 196){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.y < -2){ NSLog(@"To Left"); if (150+500*xdiff >= 148 && 150+500*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+500*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 195, 20, 20)]; }else if (150+500*xdiff <= 0){ [self.pitchDot setFrame:CGRectMake(0, 195, 20, 20)]; }else if(150+500*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; }else if(150+500*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.y > 2){ NSLog(@"To Right"); if (150+500*xdiff >= 148 && 150+500*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+500*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 195, 20, 20)]; }else if (150+500*xdiff <= 0){ [self.pitchDot setFrame:CGRectMake(0, 195, 20, 20)]; }else if(150+500*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; }else if(150+500*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x < -0.20 && currDeviceMotion.rotationRate.y > 0.20 ){ NSLog(@"To Diagonal Right Top"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 0, 20, 20)]; }else if(150+650*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195-1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 0.20 && currDeviceMotion.rotationRate.y < -0.20 ){ NSLog(@"To Diagonal Left Bottom"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff <= 0 ) { [self.pitchDot setFrame:CGRectMake(0, 390, 20, 20)]; }else if(150+650*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195-1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x < -0.20 && currDeviceMotion.rotationRate.y < -0.20 ){ NSLog(@"To Diagonal Left Top and xdiff is %f",xdiff); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff <= 0 ) { [self.pitchDot setFrame:CGRectMake(0, 0, 20, 20)]; }else if(150+650*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195+1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 0.20 && currDeviceMotion.rotationRate.y > 0.20 ){ NSLog(@"To Diagonal Right Bottom"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 390, 20, 20)]; }else if(150+650*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195+1.3*650*xdiff, 20, 20)]; } } }else if((currDeviceMotion.rotationRate.x < 0.20 && currDeviceMotion.rotationRate.x < -0.20) ||(currDeviceMotion.rotationRate.y < 0.20 && currDeviceMotion.rotationRate.y < -0.20) ||(currDeviceMotion.rotationRate.z < 0.20 && currDeviceMotion.rotationRate.z < -0.20)){ [self.rollDot setFrame:CGRectMake(150, 195, 20, 20)]; [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; } It could be great if i could make it move like the application i have stated above, called Gyrododge This link also addresses a similar question:Link. Any advice or help is greatly appreciated... Thanks.

    Read the article

  • Act on click of a button on the Nav Bar for moreNavigationController -- Can't pushviewcontroller

    - by Jann
    Okay, here is my issue: My app has a display of categories in the tab bar at the bottom of the iPhoneOS screen. This only allows 5 categories before it presents the MORE button. I have over 25 (please do not answer this by saying: "Rethink your application...etc" -- that was rudely said before. They are food, drink, etc categories and cannot be changed). I want to allow the user to put their favorites on the home page. The Apple moreNavigationController editing system only allows 20 tab bar items to be rearranged due to space constraints on the editing page. This is not enough so i need to implement my own Editing screen. I set the rightBarButtonItem to nil and created my own. Using NSLog, i can see the "click" happens when clicking the EDIT button, but I cannot push using pushViewController. Nothing happens. I think it has something to do with the navigationController I am addressing...but i am not sure. ps: This all happens in my App Delegate which DOES act as both UITabBarControllerDelegate & UINavigationControllerDelegate. I tried to do the following: - ( void )navigationController:( UINavigationController * )navigationController_local willShowViewController:( UIViewController * )viewController_local animated:( BOOL )animated { UIViewController * currentController = navigationController_local.visibleViewController; UIViewController * nextController = viewController_local; // Do whatever here. NSLog(@"Nav contoller willShowViewController fired\n'%@'\n'%@'\nThere are currently: %d views on the stack\n",currentController,nextController,[self.navigationController.viewControllers count]); if ( [nextController isKindOfClass:NSClassFromString(@"UIMoreListController")]) { UINavigationBar *morenavbar = navigationController_local.navigationBar; UINavigationItem *morenavitem = morenavbar.topItem; morenavitem.rightBarButtonItem = nil; NSLog(@"Is a UIMoreListController\n"); UIBarButtonItem *editTabBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStylePlain target:self action:@selector(editTabBar:)]; morenavitem.rightBarButtonItem = editTabBarButton; [editTabBarButton release]; } } This works to place an EDIT button at the top right of the screen -- mimicking Apple's look and feel... but when that button is clicked, you cannot exit the darn moreNavigationController. I have tried many things. UIAlerts work, etc...but pushing (or popping -- even popping to root view) a view controller on the stack does not. - (void) editTabBar:(id)sender { NSLog(@"clicked edit tabbar\n"); NSLog(@"Total count of controllers: %d\n",[self.navigationController.viewControllers count]); TabBarViewController *tabBarViewController2 = [[TabBarViewController alloc] initWithNibName:@"TabBarView" bundle:nil]; tabBarViewController2.navigationItem.title=@"Edit Tab Bar"; [self.navigationController pushViewController:tabBarViewController2 animated:YES]; [tabBarViewController2 release]; NSLog(@"finished edit tabbar\n"); } If you click the edit button on the moreNavigationController's display page, you get the log entries like expected AND (this is strange) the views on the stack climbs -- but no page change occurs. I marked it down to not using the correct navigation controller...but I am lost on how to find which one TO use. this is a weird one too. In the edit function if i just do this: - (void) editTabBar:(id)sender { self.tabBarController.selectedIndex = 0; } It DOES take me home (to tabbarcontroller 0) BUT doing this: - (void) editTabBar:(id)sender { [self.navigationController popToRootViewControllerAnimated:YES]; } does not work. Does the moreNavigationController have some special quality that screws with the rest of the system?

    Read the article

  • How to change by using CVGrayscaleMat

    - by Babul
    With the following code the image showed as above is converted as below image... Their it's showing black background with gray lines.....i want white background with gray lines .. Please guide me .. i am new to iPhone Thanks alot in Advance - (void)viewDidLoad { [super viewDidLoad]; // Initialise video capture - only supported on iOS device NOT simulator #if TARGET_IPHONE_SIMULATOR NSLog(@"Video capture is not supported in the simulator"); #else _videoCapture = new cv::VideoCapture; if (!_videoCapture->open(CV_CAP_AVFOUNDATION)) { NSLog(@"Failed to open video camera"); } #endif // Load a test image and demonstrate conversion between UIImage and cv::Mat UIImage *testImage = [UIImage imageNamed:@"testimage.jpg"]; double t; int times = 10; //-------------------------------- // Convert from UIImage to cv::Mat NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { cv::Mat tempMat = [testImage CVMat]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; [pool release]; NSLog(@"UIImage to cv::Mat: %gms", t); //------------------------------------------ // Convert from UIImage to grayscale cv::Mat pool = [[NSAutoreleasePool alloc] init]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { cv::Mat tempMat = [testImage CVGrayscaleMat]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; [pool release]; NSLog(@"UIImage to grayscale cv::Mat: %gms", t); //-------------------------------- // Convert from cv::Mat to UIImage cv::Mat testMat = [testImage CVMat]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { UIImage *tempImage = [[UIImage alloc] initWithCVMat:testMat]; [tempImage release]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; NSLog(@"cv::Mat to UIImage: %gms", t); // Process test image and force update of UI _lastFrame = testMat; [self sliderChanged:nil]; } - (IBAction)capture:(id)sender { if (_videoCapture && _videoCapture->grab()) { (*_videoCapture) >> _lastFrame; [self processFrame]; } else { NSLog(@"Failed to grab frame"); } } - (void)processFrame { double t = (double)cv::getTickCount(); cv::Mat grayFrame, output; // Convert captured frame to grayscale cv::cvtColor(_lastFrame, grayFrame, cv::COLOR_RGB2GRAY); // Perform Canny edge detection using slide values for thresholds cv::Canny(grayFrame, output, _lowSlider.value * kCannyAperture * kCannyAperture, _highSlider.value * kCannyAperture * kCannyAperture, kCannyAperture); t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency(); // Display result self.imageView.image = [UIImage imageWithCVMat:output]; self.elapsedTimeLabel.text = [NSString stringWithFormat:@"%.1fms", t]; }

    Read the article

  • How to display a person record just after saving his data to iPhone Address Book?

    - by camelCase
    this is my code and it works flawless, where my_value is a string with separator ','. everythign works fin but i'd like to display the person record from the address book after i saved it, so in the function if(isSaved) { // **** code here *** } here the complete function - (void) addToAgenda: (NSString*) my_value{ //NSArray *strings = [my_value componentsSeparatedByString: @","]; NSArray *dati=[[NSArray alloc] initWithArray:[my_value componentsSeparatedByString:@","]]; NSString *userwebsite = [dati objectAtIndex:0]; NSString *fname = [dati objectAtIndex:1]; NSString *lname = [dati objectAtIndex:2]; NSString *useremail = [dati objectAtIndex:3];; NSString *usermobile = [dati objectAtIndex:4]; NSString *usercompany = @"xxx"; ABRecordRef aRecord = ABPersonCreate(); CFErrorRef anError = NULL; // fisrst name ABRecordSetValue(aRecord, kABPersonFirstNameProperty, fname, &anError); // last name ABRecordSetValue(aRecord, kABPersonLastNameProperty, lname, &anError); // Phone Number. ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(multi, (CFStringRef)usermobile, kABWorkLabel, NULL); ABRecordSetValue(aRecord, kABPersonPhoneProperty, multi, &anError); CFRelease(multi); // Company ABRecordSetValue(aRecord, kABPersonDepartmentProperty, usercompany, &anError); // email NSLog(@"%@", useremail); ABMutableMultiValueRef multiemail = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(multiemail, (CFStringRef)useremail, kABWorkLabel, NULL); ABRecordSetValue(aRecord, kABPersonEmailProperty, multiemail, &anError); CFRelease(multiemail); // website NSLog(@"%@", userwebsite); ABMutableMultiValueRef multiweb = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(multiweb, (CFStringRef)userwebsite, kABWorkLabel, NULL); ABRecordSetValue(aRecord, kABPersonURLProperty, multiweb, &anError); CFRelease(multiemail); if (anError != NULL) NSLog(@"error while creating.."); CFStringRef personname, personlname, personcompind, personemail, personwebsite, personcontact; personname = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty); personlname = ABRecordCopyValue(aRecord, kABPersonLastNameProperty); personcompind = ABRecordCopyValue(aRecord, kABPersonDepartmentProperty); personemail = ABRecordCopyValue(aRecord, kABPersonEmailProperty); personwebsite = ABRecordCopyValue(aRecord, kABPersonURLProperty); personcontact = ABRecordCopyValue(aRecord, kABPersonPhoneProperty); ABAddressBookRef addressBook; CFErrorRef error = NULL; addressBook = ABAddressBookCreate(); BOOL isAdded = ABAddressBookAddRecord (addressBook, aRecord, &error); if(isAdded){ NSLog(@"added.."); } if (error != NULL) { NSLog(@"ABAddressBookAddRecord %@", error); } error = NULL; BOOL isSaved = ABAddressBookSave (addressBook, &error); if(isSaved) { // **** code here *** } if (error != NULL) { NSLog(@"ABAddressBookSave %@", error); UIAlertView *alertOnChoose = [[UIAlertView alloc] initWithTitle:@"Unable to save this time" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil]; [alertOnChoose show]; [alertOnChoose release]; } CFRelease(aRecord); CFRelease(personname); CFRelease(personlname); CFRelease(personcompind); CFRelease(personcontact); CFRelease(personemail); CFRelease(personwebsite); CFRelease(addressBook); }

    Read the article

  • Unable to use NSURLConnection to get contents of password/username protected webpage

    - by bubster
    I am trying to get the contents of a webpage that requires a password and user name to access. I am using a NSURLConnection object to get it however when I write the NSMutableData object that is returned to a file all I get is the login page. Normally when you try to load the password protected page when you are not logged in it redirects to the login page however I thought that if I provided valid credentials then this I would be able to view the password protected page. Also I do not know if it is relevant the website is using a microsoft mysql database on an IIS (internet information server). Note: [protectionSpace authenticationMethod] returns NSURLAuthenticationMethodServerTrust I am pretty unfamiliar with this so any ideas would be greatly appreciated. Below is all of the relevant code: - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // This method is called when the server has determined that it // has enough information to create the NSURLResponse. // It can be called multiple times, for example in the case of a // redirect, so each time we reset the data. // receivedData is an instance variable declared elsewhere. [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Append the new data to receivedData. // receivedData is an instance variable declared elsewhere. [receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // release the connection, and the data object //[connection release]; // receivedData is declared as a method instance elsewhere //[receivedData release]; // inform the user NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // do something with the data // receivedData is declared as a method instance elsewhere NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); // release the connection, and the data object //[connection release]; //[receivedData release]; //Write data to a file [receivedData writeToFile:@"/Users/matsallen/Desktop/receivedData.html" atomically:YES]; } - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace: (NSURLProtectionSpace *)protectionSpace { NSLog(@"The connection encountered a protection space. The authentication method is %@", [protectionSpace authenticationMethod]); secureTrustReference = [protectionSpace serverTrust]; //SecTrustResultType *result; //OSStatus status = SecTrustEvaluate(secureTrustReference, result); //NSLog(@"Result of the trust evaluation is %@",status); return YES; } - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSURLCredential *newCredential; newCredential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]; newCredential = [NSURLCredential credentialForTrust:secureTrustReference]; // [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; // [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } #pragma mark - View lifecycle - (void)viewDidLoad { receivedData = [[NSMutableData alloc] init]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.markallenonline.com/secure/maoCoaching.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [NSMutableData data]; NSLog(@"Connection succeeded!"); } else { // Inform the user that the connection failed. NSLog(@"Connection failed!"); } }

    Read the article

  • Find out when all processes in (void) is done?

    - by Emil
    Hey. I need to know how you can find out when all processes (loaded) from a - (void) are done, if it's possible. Why? I'm loading in data for a UITableView, and I need to know when a Loading... view can be replaced with the UITableView, and when I can start creating the cells. This is my code: - (void) reloadData { NSAutoreleasePool *releasePool = [[NSAutoreleasePool alloc] init]; NSLog(@"Reloading data."); NSURL *urlPosts = [NSURL URLWithString:[NSString stringWithFormat:@"%@", URL]]; NSError *lookupError = nil; NSString *data = [[NSString alloc] initWithContentsOfURL:urlPosts encoding:NSUTF8StringEncoding error:&lookupError]; postsData = [data componentsSeparatedByString:@"~"]; [data release], data = nil; urlPosts = nil; self.numberOfPosts = [[postsData objectAtIndex:0] intValue]; self.postsArrayID = [[postsData objectAtIndex:1] componentsSeparatedByString:@"#"]; self.postsArrayDate = [[postsData objectAtIndex:2] componentsSeparatedByString:@"#"]; self.postsArrayTitle = [[postsData objectAtIndex:3] componentsSeparatedByString:@"#"]; self.postsArrayComments = [[postsData objectAtIndex:4] componentsSeparatedByString:@"#"]; self.postsArrayImgSrc = [[postsData objectAtIndex:5] componentsSeparatedByString:@"#"]; NSMutableArray *writeToPlist = [NSMutableArray array]; NSMutableArray *writeToNoImagePlist = [NSMutableArray array]; NSMutableArray *imagesStored = [NSMutableArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]; int loop = 0; for (NSString *postID in postsArrayID) { if ([imagesStored containsObject:[NSString stringWithFormat:@"%@.png", postID]]){ NSLog(@"Allready stored, jump to next. ID: %@", postID); continue; } NSLog(@"%@.png", postID); NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[postsArrayImgSrc objectAtIndex:loop]]]; // If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB if (imageData == nil){ NSLog(@"imageData is empty before trying .jpeg"); // If image == nil, try to replace .jpg with .jpeg, and if that worked, set cellImage to that image. If that is also nil, use noImage.png, set in IB. imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[postsArrayImgSrc objectAtIndex:loop] stringByReplacingOccurrencesOfString:@".jpg" withString:@".jpeg"]]]; } if (imageData != nil){ NSLog(@"imageData is NOT empty when creating file"); [fileManager createFileAtPath:[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"images/%@.png", postID]] contents:imageData attributes:nil]; [writeToPlist addObject:[NSString stringWithFormat:@"%@.png", postID]]; } else { [writeToNoImagePlist addObject:[NSString stringWithFormat:@"%@", postID]]; } imageData = nil; loop++; NSLog(@"imagePlist: %@\nnoImagePlist: %@", writeToPlist, writeToNoImagePlist); } NSMutableArray *writeToAllPlist = [NSMutableArray arrayWithArray:writeToPlist]; [writeToPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:nowPlist]]; [writeToAllPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]]; [writeToNoImagePlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"]]]; [writeToPlist writeToFile:nowPlist atomically:YES]; [writeToAllPlist writeToFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"] atomically:YES]; [writeToNoImagePlist writeToFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"] atomically:YES]; [releasePool release]; }

    Read the article

  • Admob banner not getting remove from superview

    - by Anil gupta
    I am developing one 2d game using cocos2d framework, in this game i am using admob for advertising, in some classes not in all classes but admob banner is visible in every class and after some time game getting crash also. I am not getting how admob banner is comes in every class in fact i have not declare in Rootviewcontroller class. can any one suggest me how to integrate Admob in cocos2d game, i want Admob banner in particular classes not in every class, I am using latest google admob sdk, my code is below: Thanks in advance ` -(void)AdMob{ NSLog(@"ADMOB"); CGSize winSize = [[CCDirector sharedDirector]winSize]; // Create a view of the standard size at the bottom of the screen. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ bannerView_ = [[GADBannerView alloc] initWithFrame:CGRectMake(size.width/2-364, size.height - GAD_SIZE_728x90.height, GAD_SIZE_728x90.width, GAD_SIZE_728x90.height)]; } else { // It's an iPhone bannerView_ = [[GADBannerView alloc] initWithFrame:CGRectMake(size.width/2-160, size.height - GAD_SIZE_320x50.height, GAD_SIZE_320x50.width, GAD_SIZE_320x50.height)]; } if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { bannerView_.adUnitID =@"a15062384653c9e"; } else { bannerView_.adUnitID =@"a15062392a0aa0a"; } bannerView_.rootViewController = self; [[[CCDirector sharedDirector]openGLView]addSubview:bannerView_]; [bannerView_ loadRequest:[GADRequest request]]; GADRequest *request = [[GADRequest alloc] init]; request.testing = [NSArray arrayWithObjects: GAD_SIMULATOR_ID, nil]; // Simulator [bannerView_ loadRequest:request]; } //best practice for removing the barnnerView_ -(void)removeSubviews{ NSArray* subviews = [[CCDirector sharedDirector]openGLView].subviews; for (id SUB in subviews){ [(UIView*)SUB removeFromSuperview]; [SUB release]; } NSLog(@"remove from view"); } //this makes the refreshTimer count -(void)targetMethod:(NSTimer *)theTimer{ //INCREASE OF THE TIMER AND SECONDS elapsedTime++; seconds++; //INCREASE OF THE MINUTOS EACH 60 SECONDS if (seconds>=60) { seconds=0; minutes++; [self removeSubviews]; [self AdMob]; } NSLog(@"TIME: %02d:%02d", minutes, seconds); } `

    Read the article

  • Identify which CCSprite is touched in Cocos2d

    - by PeterK
    I am trying to learn Cocos2d and is experimenting with Ray Wenderlich tutorial whack-a-mole: www.raywenderlich.com/2560/how-to-create-a-mole-whacking-game-with-cocos2d-part-1 In this tutorial three CCSprite's are popping up and you should click on them... However, i am trying to identify which mole, rat in my case, is popping up and place a CCSprite above that. Initially this looked like an easy task but i am failing. I am trying to NSLog LEFT HIT. i would guess the problem is in the If-statement and the last "227" height parameter. The left rat boundingBox = {{99.5, 146.5}, {165, 227}} (from NSLog). The key code is in the ccTouchBegan function: -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; for (CCSprite *rat in rats) { if (rat.userData == FALSE) continue; if (CGRectContainsPoint(rat.boundingBox, touchLocation)) { //left: rat boundingBox = {{99.5, 146.5}, {165, 227}} //mid: rat boundingBox = {{349.5, 146.5}, {165, 227}} //right: rat boundingBox = {{599.5, 146.5}, {165, 227}} //>>>>Here is where i try to get a hit<<<< if (CGRectContainsPoint(CGRectMake(99.5, 146.55, 165, 227), touchLocation)) { NSLog(@">>>>HIT LEFT<<<<<"); } I would really appreciate a few ideas how to get this to work.

    Read the article

  • UIViewController not loading a UIView

    - by Cosizzle
    Hey, I'm playing around with a script my teacher provided for a table based application. However I can't seem to get my own view to load. Files: SubViewOneController (which is a sub view, also has a nib) TapViewController (Custom UIView I created and want to add to a cell) RootViewController (Main controller which loads in the views) SimpleNavAppDelegate How it works: Within the RootViewController, there's an NSArray that holds NSDictionary objects which is declared in the -(void)awakeFromNib {} method - (void)awakeFromNib { // we'll keep track of our views controllers in this array views = [[NSMutableArray alloc] init]; // when using alloc you are responsible for it, and you will have to release it. // ==================================================================================================== // ==================================================================================================== // LOADING IN CUSTOM VIEW HERE: // allocate a set of views and add to our view array as a dictionary item TapViewController *tapBoardView = [[TapViewController alloc] init]; //push onto array [views addObject:[NSDictionary dictionaryWithObjectsAndKeys: @"Tab Gestures", @"title", tapBoardView, @"controller", nil]]; [tapBoardView release]; //release the memory // ==================================================================================================== // ==================================================================================================== SubViewOneController *subViewOneController = [[SubViewOneController alloc] init]; // This will set the 2nd level title subViewOneController.title = @"Swipe Gestures"; //set it's title //push it onto the array [views addObject:[NSDictionary dictionaryWithObjectsAndKeys: @"Swipe Gestures", @"title", subViewOneController, @"controller", nil]]; [subViewOneController release]; //release the memory } Later on I set the table view: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // OUTPUT -- see console NSLog(@"indexPath %i", indexPath.row); // OUTPUT: tapController: <TapViewController: 0x3b2b360> NSLog(@"view object: %@", [views objectAtIndex:indexPath.row]); // OUTPUT: view object: controller = <TapViewController: 0x3b0e290>; title = "Tab Gestures"; // ----- Hardcoding the controller and nib file in does work, so it's not a linkage issue ------ // UNCOMMENT TO SEE WORKING -- comment below section. //TapViewController *tapContoller = [[TapViewController alloc] initWithNibName:@"TapBoardView" bundle:nil]; //NSLog(@"tapController: %@", tapContoller); //[self.navigationController pushViewController:tapContoller animated:YES]; // ----- Random Tests ----- //UIViewController *targetViewController = [[views objectAtIndex: 0] objectForKey:@"controller"]; // DOES NOT WORK // LOADS THE SECOND CELL (SubViewOneController) however will not load (TapViewController) UIViewController *targetViewController = [[views objectAtIndex: indexPath.row] objectForKey:@"controller"]; NSLog(@"target: %@", targetViewController); // OUTPUT: target: <TapViewController: 0x3b0e290> [self.navigationController pushViewController:targetViewController animated:YES]; } Reading the comments you should be able to see that hardcoding the view in, works - however trying to load it from the View NSArray does not work. It does however contain the object in memory, seeing that NSLog proves that. Everything is linked up and working within the TapViewController nib file. So ya, im kinda stuck on this one, any help would be great! Thanks guys

    Read the article

  • Cancel UITouch Events When View Covered By Modal UIViewController

    - by kkrizka
    Hi there, I am writing an application where the user has to move some stuff on the screen using his fingers and drop them. To do this, I am using the touchesBegan,touchesEnded... function of each view that has to be moved. The problem is that sometimes the views are covered by a view displayed using the [UIViewController presentModalViewController] function. As soon as that happens, the UIView that I was moving stops receiving the touch events, since it was covered up. But there is no event telling me that it stopped receiving the events, so I can reset the state of the moved view. The following is an example that demonstrates this. The functions are part of a UIView that is being shown in the main window. It listens to touch events and when I drag the finger for some distance, it presents a modal view that covers everything. In the Run Log, it prints what touch events are received. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesBegan"); touchStart=[[touches anyObject] locationInView:self]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint touchAt=[[touches anyObject] locationInView:self]; float xx=(touchAt.x-touchStart.x)*(touchAt.x-touchStart.x); float yy=(touchAt.y-touchStart.y)*(touchAt.y-touchStart.y); float rr=xx+yy; NSLog(@"touchesMoved %f",rr); if(rr > 100) { NSLog(@"Show modal"); [viewController presentModalViewController:[UIViewController new] animated:NO]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesEnded"); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesCancelled"); } But when I test the application and trigger the modal dialog to be displayed, the following is the output in the Run Log. [Session started at 2010-03-27 16:17:14 -0700.] 2010-03-27 16:17:18.831 modelTouchCancel[2594:207] touchesBegan 2010-03-27 16:17:19.485 modelTouchCancel[2594:207] touchesMoved 2.000000 2010-03-27 16:17:19.504 modelTouchCancel[2594:207] touchesMoved 4.000000 2010-03-27 16:17:19.523 modelTouchCancel[2594:207] touchesMoved 16.000000 2010-03-27 16:17:19.538 modelTouchCancel[2594:207] touchesMoved 26.000000 2010-03-27 16:17:19.596 modelTouchCancel[2594:207] touchesMoved 68.000000 2010-03-27 16:17:19.624 modelTouchCancel[2594:207] touchesMoved 85.000000 2010-03-27 16:17:19.640 modelTouchCancel[2594:207] touchesMoved 125.000000 2010-03-27 16:17:19.641 modelTouchCancel[2594:207] Show modal Any suggestions on how to reset the state of a UIView when its touch events are interrupted by a modal view?

    Read the article

  • Objective-c - How to serialize audio file into small packets that can be played?

    - by vfn
    Hi there, So, I would like to get a sound file and convert it in packets, and send it to another computer. I would like that the other computer be able to play the packets as they arrive. I am using AVAudioPlayer to try to play this packets, but I couldn't find a proper way to serialize the data on the peer1 that the peer2 can play. The scenario is, peer1 has a audio file, split the audio file in many small packets, put them on a NSData and send them to peer2. Peer 2 receive the packets and play one by one, as they arrive. Does anyone have know how to do this? or even if it is possible? EDIT: Here it is some piece of code to illustrate what I would like to achieve. // This code is part of the peer1, the one who sends the data - (void)sendData { int packetId = 0; NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"myAudioFile" ofType:@"wav"]; NSData *soundData = [[NSData alloc] initWithContentsOfFile:soundFilePath]; NSMutableArray *arraySoundData = [[NSMutableArray alloc] init]; // Spliting the audio in 2 pieces // This is only an illustration // The idea is to split the data into multiple pieces // dependin on the size of the file to be sent NSRange soundRange; soundRange.length = [soundData length]/2; soundRange.location = 0; [arraySoundData addObject:[soundData subdataWithRange:soundRange]]; soundRange.length = [soundData length]/2; soundRange.location = [soundData length]/2; [arraySoundData addObject:[soundData subdataWithRange:soundRange]]; for (int i=0; i // This is the code on peer2 that would receive an play the piece of audio on each packet - (void) receiveData:(NSData *)data { NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; if ([unarchiver containsValueForKey:PACKET_ID]) NSLog(@"DECODED PACKET_ID: %i", [unarchiver decodeIntForKey:PACKET_ID]); if ([unarchiver containsValueForKey:PACKET_SOUND_DATA]) { NSLog(@"DECODED sound"); NSData *sound = (NSData *)[unarchiver decodeObjectForKey:PACKET_SOUND_DATA]; if (sound == nil) { NSLog(@"sound is nil!"); } else { NSLog(@"sound is not nil!"); AVAudioPlayer *audioPlayer = [AVAudioPlayer alloc]; if ([audioPlayer initWithData:sound error:nil]) { [audioPlayer prepareToPlay]; [audioPlayer play]; } else { [audioPlayer release]; NSLog(@"Player couldn't load data"); } } } [unarchiver release]; } So, here is what I am trying to achieve...so, what I really need to know is how to create the packets, so peer2 can play the audio. It would be a kind of streaming. Yes, for now I am not worried about the order that the packet are received or played...I only need to get the sound sliced and them be able to play each piece, each slice, without need to wait for the whole file be received by peer2. Thanks!

    Read the article

  • Properly setting up willSelectRowAtIndexPath and didSelectRowAtIndexPath to send cell selections

    - by Gordon Fontenot
    Feel like I'm going a bit nutty here. I have a detail view with a few stand-alone UITextFields, a few UITextFields in UITAbleViewCells, and one single UITableViewCell that will be used to hold notes, if there are any. I only want this cell selectable when I am in edit mode. When I am not in edit mode, I do not want to be able to select it. Selecting the cell (while in edit mode) will fire a method that will init a new view. I know this is very easy, but I am missing something somewhere. Here are the current selection methods I am using: -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (!self.editing) { NSLog(@"Returning nil, not in edit mode"); return nil; } NSLog(@"Cell will be selected, not in edit mode"); if (indexPath.section == 0) { NSLog(@"Comments cell will be selected"); return indexPath; } return nil; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (!self.editing) { NSLog(@"Not in edit mode. Should not have made it this far."); return; } if (indexPath.section == 0) [self pushCommentsView]; else return; } My problem is really 2 fold; 1) Even when I'm not in edit mode, and I know I am returning nil (due to the NSLog message), I can still select the row (it flashes blue). From my understanding of the willSelectRowAtIndexPath method, this shouldn't be happening. Maybe I am wrong about this? 2) When I enter edit mode, I can't select anything at all. the willSelectRowAtIndexPath method never fires, and neither does the didSelectRowAtIndexPath. The only thing I am doing in the setEditing method, is hiding the back button while editing, and assigning firstResponder to the top textField to get the keyboard to pop up. I thought maybe the first responder was getting in the way of the click (which would be dumb), but even with that commented out, I cannot perform the cell selection during editing.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >