Search Results

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

Page 13/63 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Objective-C Passing a variable to another IBAction

    - by StuR
    This works fine: NSString *myVariable; - (IBAction) doFirstAction { myVariable = @"123456789"; } - (IBAction) doSecondAction { NSLog(@"%@",myVariable); } However, if I do this (substituting the @"123456789" for some code which returns the same value ie "123456789") I cannot access the value in doSecondAction. NSString *myVariable; - (IBAction) doFirstAction { myVariable = [imageNode getAttributeName:@"value"]; } - (IBAction) doSecondAction { NSLog(@"%@",myVariable); } Any clue as to why I cant access myVariable outside of doFirstAction?

    Read the article

  • How to replace an object in an NSMutableArray at a given index with a new object

    - by shakeelw
    Hi guys. I have an NSMutableArray object(retained, synthesized as all) that is initiated just fine and I can easily add objects to it using the 'addObject:' method. But if I want to replace an object at a certain index with a new one in that NSMutableArray, it doesn't work. For example: ClassA.h @interface ClassA : NSObject { NSMutableArray *list; } @property (nonatomic, copy, readwrite) NSMutableArray *list; end ClassA.m import "ClassA.h" @implementation ClassA @synthesize list; (id)init { [super init]; NSMutableArray *localList = [[NSMutableArray alloc] init]; self.list = localList; [localList release]; //Add initial data [list addObject:@"Hello "]; [list addObject:@"World"]; } // Custom set accessor to ensure the new list is mutable (void)setList:(NSMutableArray *)newList { if (list != newList) { [list release]; list = [newList mutableCopy]; } } -(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex { int i = [theIndex intValue]-1; [self.list replaceObjectAtIndex:i withObject:newTitle]; NSLog((NSString *)[self.list objectAtIndex:i]); // gives the correct output } However, the change remains true only inside the method. from any other method, the NSLog((NSString *)[self.list objectAtIndex:i]); gives the same old value. How can I actually get the old object replaced with the new one at a specific index so that the change can be noticed from within any other method as well. I even modified the method like this, but the result is the same: -(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex { int i = [theIndex intValue]-1; NSMutableArray *localList = [[NSMutableArray alloc] init]; localList = [localList mutableCopy]; for(int j = 0; j < [list count]; j++) { if(j == i) { [localList addObject:newTitle]; NSLog(@"j == 1"); NSLog([NSString stringWithFormat:@"%d", j]); } else { [localList addObject:(NSString *)[self.list objectAtIndex:j]]; } } [self.list release]; //self.list = [localList mutableCopy]; [self setList:localList]; [localList release]; } Please help out guys :)

    Read the article

  • "incomplete universal character name" with stringWithUTF8String

    - by Nasser
    hi, when i try to convert form utf-8 string to NSString like so: NSString *s = [NSString stringWithUTF8String:"\U0627\U0644\U0641\U0631\U0646"]; NSLog(@"%@", s); i get the compile error: incomplete universal character name note that it sometime just works fine: NSString *UAE = [NSString stringWithUTF8String:"\U0627\U0644\U0641\U0631\U0646"]; NSLog(@"%@", UAE); and the output: ???????? so why is that happening? please help.

    Read the article

  • Iphone release problem

    - by xger86x
    Hi, i have the following code in a .h @property (nonatomic, copy) NSString *username; Then, username is assigned in this way when the user enter text in a TextField: self.username = textField.text; And then, in dealloc method i call release: NSLog(@"%d",[username retainCount]); [username release]; NSLog(@"%d",[username retainCount]); But in the console it prints: 2011-01-11 23:09:52.468 IApp[2527:307] 1 2011-01-11 23:09:52.480 IApp[2527:307] 1 What is the problem? Thanks

    Read the article

  • NSString cannot be released

    - by Stanley
    Consider the following method and the caller code block. The method analyses a NSString and extracts a "http://" string which it passes out by reference as an auto release object. Without releasing g_scan_result, the program works as expected. But according to non-arc rules, g_scan_result should be released since a retain has been called against it. My question are : Why g_scan_result cannot be released ? Is there anything wrong the way g_scan_result is handled in the posted coding below ? Is it safe not to release g_scan_result as long as the program runs correctly and the XCode Memory Leak tool does not show leakage ? Which XCode profile tools should I look into to check and under which subtitle ? Hope somebody knowledgeable could help. - (long) analyse_scan_result :(NSString *)scan_result target_url :(NSString **)targ_url { NSLog (@" RES analyse string : %@", scan_result); NSRange range = [scan_result rangeOfString:@"http://" options:NSCaseInsensitiveSearch]; if (range.location == NSNotFound) { *targ_url = @""; NSLog(@"fnd string not found"); return 0; } NSString *sub_string = [scan_result substringFromIndex : range.location]; range = [sub_string rangeOfString : @" "]; if (range.location != NSNotFound) { sub_string = [sub_string substringToIndex : range.location]; } NSLog(@" FND sub_string = %@", sub_string); *targ_url = sub_string; return [*targ_url length]; } The following is the caller code block, also note that g_scan_result has been declared and initialized (on another source file) as : NSString *g_scan_result = nil; Please do send a comment or answer if you have suggestions or find possible errors in code posted here (or above). Xcode memory tools does not seem to show any memory leak. But it may be because I do not know where to look as am new to the memory tools. { long url_leng = [self analyse_scan_result:result target_url:&targ_url]; NSLog(@" TAR target_url = %@", targ_url); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Scanned Result" message:result delegate:g_alert_view_delegate cancelButtonTitle:@"OK" otherButtonTitles:nil]; if (url_leng) { // ****** The 3 commented off statements // ****** cannot be added without causing // ****** a crash after a few scan result // ****** cycles. // ****** NSString *t_url; if (g_system_status.language_code == 0) [alert addButtonWithTitle : @"Open"]; else if (g_system_status.language_code == 1) [alert addButtonWithTitle : @"Abrir"]; else [alert addButtonWithTitle : @"Open"]; // ****** t_url = g_scan_result; g_scan_result = [targ_url retain]; // ****** [t_url release]; } targ_url = nil; [alert show]; [alert release]; [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(activate_qr_scanner:) userInfo:nil repeats:NO ]; return; }

    Read the article

  • How can i use a variable created in a objective c Void function?

    - by James
    Im trying to get the lat and long values generated in a void function and use them within another function. Any help grateful. (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { float latDeg = newLocation.coordinate.latitude; NSLog(@"Lat: %g", latDeg); float longDeg = newLocation.coordinate.longitude; NSLog(@"Lat: %g", longDeg); } I want to use the latDeg and longDeg variables.

    Read the article

  • Can't record or play with a simple recorder?

    - by user1280535
    I have 2 classes, a record and a player. In my main scene, I create an instance of them and play and record. But, as I see, it only records and somehow does not play (the file is not there!) Here is the code for both : -(void)record { NSArray *dirPaths; NSString *docsDir; NSString *sound= @"sound0.caf" ; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath = [docsDir stringByAppendingPathComponent:sound]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0], AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil]; NSError *error; myRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:settings error:&error]; if (myRecorder) { NSLog(@"rec"); [myRecorder prepareToRecord]; myRecorder.meteringEnabled = YES; [myRecorder record]; } else NSLog( @"error" ); } I can see the log of rec. -(void)play { NSArray *dirPaths; NSString *docsDir; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath1 = @"sound0.caf" ; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath1]; BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:soundFilePath1]; if(isMyFileThere) { NSLog(@"PLAY"); avPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:NULL]; avPlayer1.volume = 8.0; avPlayer1.delegate = self; [avPlayer1 play]; } } I DONT SEE THE LOG OF PLAY ! I call them both with: recInst=[recorder alloc]; //to rec [recInst record]; plyInst=[player alloc]; //play [plyInst play]; and to stop the recorder: - (void)stopRecorder { NSLog(@"stopRecordings"); [myRecorder stop]; //[myRecorder release]; } What's wrong here? Thanks.

    Read the article

  • search substring from mutable array in iphone

    - by user566431
    how to search substring from mutable array? NSMutableArrray names having string values, searchText is a substring to search from name array values. for (NSString *sTemp in names) { NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch]; //NSLog(@"sTemp = %@, searchText = %@",sTemp,searchText); NSLog(@"%@",titleResultsRange.length); if (titleResultsRange.length > 0) [Items addObject:sTemp]; }

    Read the article

  • UITableView issue when using separate delegate/dataSource

    - by Adam Alexander
    General Description: To start with what works, I have a UITableView which has been placed onto an Xcode-generated view using Interface Builder. The view's File Owner is set to an Xcode-generated subclass of UIViewController. To this subclass I have added working implementations of numberOfSectionsInTableView: tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: and the Table View's dataSource and delegate are connected to this class via the File Owner in Interface Builder. The above configuration works with no problems. The issue occurs when I want to move this Table View's dataSource and delegate implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class. To accomplish this, I try the following: Create a new subclass of UITableViewController in Xcode Move the known-good implementations of numberOfSectionsInTableView: tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: to the new subclass Drag a Table View Controller to the top level of the existing XIB in InterfaceBuilder, delete the View/TableView that are automatically created for this Table View Controller, then set the Table View Controller's class to match the new subclass Remove the previously-working Table View's existing dataSource and delegate connections and connect them to the new Table View Controller When complete, I do not have a working Table View. I end up with one of three outcomes which can seemingly happen at random: When the Table View loads, I get a runtime error indicating I am sending tableView:cellForRowAtIndexPath: to an object which does not recognize it When the Table View loads, the project breaks into the debugger without error There is no error, but the Table View does not appear With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view). I added some NSLog calls and found that although numberOfSectionsInTableView and numberOfRowsInSection are both getting called, cellForRowAtIndexPath is not. I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have. If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project. Thanks for your time! Complete steps to reproduce: Create a new iPhone OS, View-Based Application in Xcode and call it TableTest Open TableTestViewController.xib in Interface Builder and drag a Table View onto the provided view surface. Connect the Table View's dataSource and delegate outlets to File's Owner, which should already represent the TableTestViewController class. Save your changes Back in Xcode, add the following code to TableTestViewController.m: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSLog(@"Returning num sections"); return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"Returning num rows"); return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Trying to return cell"); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.text = @"Hello"; NSLog(@"Returning cell"); return cell; } Build and Go, and you should see the word Hello appear in the TableView Now to attempt to move this TableView's logic out to a separate class, first create a new file in Xcode, choosing UITableViewController subclass and calling the class TableTestTableViewController Remove the above code snippet from TableTestViewController.m and place it into TableTestTableViewController.m, replacing the default implementation of these three methods with ours. Back in Interface Builder within the same TableTestViewController.xib file, drag a Table View Controller into the main IB window and delete the new Table View object that automatically came with it Set the class for this new Table View Controller to TableTestTableViewController Remove the dataSource and delegate bindings from the existing, previously-working Table View and reconnect the same two bindings to the new Table Test Table View Controller we created. Save changes, Build and Go, and if you're getting the results I'm getting, note the Table View no longer functions properly Solution: With some more troubleshooting and some assistance from the iPhone Developer Forums at https://devforums.apple.com/message/5453, I've documented a solution! The main UIViewController subclass of the project needs an outlet pointing to the UITableViewController instance. To accomplish this, simply add the following to the primary view's header (TableTestViewController.h): #import "TableTestTableViewController.h" and IBOutlet TableTestTableViewController *myTableViewController; Then, in Interface Builder, connect the new outlet from File's Owner to Table Test Table View Controller in the main IB window. No changes are necessary in the UI part of the XIB. Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely. Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.

    Read the article

  • Problem in In-App purchase-consumable model

    - by kunal-dutta
    I have created a nonconsumable in app purchase item and now I want to create a consumable in-app purchase by which a user to buy it every time he uses it,and also I want to create a subscription model In-App purchase. Everything works as expected except when I buy the item more than one time, iPhone pop ups a message saying "You've already purchased the item. Do You want to buy it again?". Is It possible to disable this dialog and proceed to the actual purchase?And what will have to change in following code with different model:- in InApp purchase manager.m: @implementation InAppPurchaseManager //@synthesize purchasableObjects; //@synthesize storeObserver; @synthesize proUpgradeProduct; @synthesize productsRequest; //BOOL featureAPurchased; //BOOL featureBPurchased; //static InAppPurchaseManager* _sharedStoreManager; // self (void)dealloc { //[_sharedStoreManager release]; //[storeObserver release]; [super dealloc]; } (void)requestProUpgradeProductData { NSSet *productIdentifiers = [NSSet setWithObject:@"com.vigyaapan.iWorkOut1" ]; productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; productsRequest.delegate = self; [productsRequest start]; // we will release the request object in the delegate callback } pragma mark - pragma mark SKProductsRequestDelegate methods (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { //NSArray *products = response.products; //proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain]: nil; if (proUpgradeProduct) { NSLog(@"Product title: %@", proUpgradeProduct.localizedTitle); NSLog(@"Product description: %@", proUpgradeProduct.localizedDescription); NSLog(@"Product price: %@", proUpgradeProduct.price); NSLog(@"Product id:%@", proUpgradeProduct.productIdentifier); } /*for (NSString invalidProductId in response.invalidProductIdentifiers) { NSLog(@"Invalid product id: %@" , invalidProductId); }/ //finally release the reqest we alloc/init’ed in requestProUpgradeProductData [productsRequest release]; [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerProductsFetchedNotification object:self userInfo:nil]; } pragma - pragma Public methods /* call this method once on startup*/ (void)loadStore { /* restarts any purchases if they were interrupted last time the app was open*/ [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; /* get the product description (defined in early sections)*/ [self requestProUpgradeProductData]; } /* call this before making a purchase*/ (BOOL)canMakePurchases { return [SKPaymentQueue canMakePayments]; } /* kick off the upgrade transaction*/ (void)purchaseProUpgrade { SKPayment *payment = [SKPayment paymentWithProductIdentifier:@"9820091347"]; [[SKPaymentQueue defaultQueue] addPayment:payment]; } pragma - pragma Purchase helpers /* saves a record of the transaction by storing the receipt to disk*/ (void)recordTransaction:(SKPaymentTransaction )transaction { if ([transaction.payment.productIdentifier isEqualToString:kInAppPurchaseProUpgradeProductId]) { / save the transaction receipt to disk*/ [[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ]; [[NSUserDefaults standardUserDefaults] synchronize]; } } /* enable pro features*/ (void)provideContent:(NSString )productId { if ([productId isEqualToString:kInAppPurchaseProUpgradeProductId]) { / enable the pro features*/ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isProUpgradePurchased" ]; [[NSUserDefaults standardUserDefaults] synchronize]; } } (void)finishTransaction:(SKPaymentTransaction )transaction wasSuccessful:(BOOL)wasSuccessful { // / remove the transaction from the payment queue.*/ [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, @"transaction" , nil]; if (wasSuccessful) { /* send out a notification that we’ve finished the transaction*/ [[NSNotificationCenter defaultCenter]postNotificationName:kInAppPurchaseManagerTransactionSucceededNotification object:self userInfo:userInfo]; } else { /* send out a notification for the failed transaction*/ [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerTransactionFailedNotification object:self userInfo:userInfo]; } } (void)completeTransaction:(SKPaymentTransaction *)transaction { [self recordTransaction:transaction]; [self provideContent:transaction.payment.productIdentifier]; [self finishTransaction:transaction wasSuccessful:YES]; } (void)restoreTransaction:(SKPaymentTransaction *)transaction { [self recordTransaction:transaction.originalTransaction]; [self provideContent:transaction.originalTransaction.payment.productIdentifier]; [self finishTransaction:transaction wasSuccessful:YES]; } (void)failedTransaction:(SKPaymentTransaction )transaction { if (transaction.error.code != SKErrorPaymentCancelled) { / error!/ [self finishTransaction:transaction wasSuccessful:NO]; } else { / this is fine, the user just cancelled, so don’t notify*/ [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; } } (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { for (SKPaymentTransaction *transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchased: [self completeTransaction:transaction]; break; case SKPaymentTransactionStateFailed: [self failedTransaction:transaction]; break; case SKPaymentTransactionStateRestored: [self restoreTransaction:transaction]; break; default: break; } } } @end in SKProduct.m:- @implementation SKProduct (LocalizedPrice) - (NSString *)localizedPrice { NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [numberFormatter setLocale:self.priceLocale]; NSString *formattedString = [numberFormatter stringFromNumber:self.price]; [numberFormatter release]; return formattedString; }

    Read the article

  • Getting null value after adding objects to customClass

    - by Brian Stacks
    Ok here's my code first viewController.h @interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate> { NSMutableArray *twitterObjects; } @property (strong, nonatomic) IBOutlet UICollectionView *myCollectionView; Here is my viewController.m // // ViewController.m // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import "ViewController.h" // add accounts framework to code #import <Accounts/Accounts.h> // add social frameworks #import <Social/Social.h> #import "TwitterCustomObject.h" #import "CustomCell.h" #import "DetailViewController.h" @interface ViewController () @end @implementation ViewController -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { //CustomCell * cell = (CustomCell*)sender; //NSIndexPath *indexPath = [_myCollectionView indexPathForCell:cell]; // setting an id for view controller DetailViewController *detailViewcontroller = segue.destinationViewController; //TwitterCustomObject *newCustomClass = [twitterObjects objectAtIndex:indexPath.row]; if (detailViewcontroller != nil) { // setting the custom customClass object //detailViewcontroller.myNewCurrentClass = newCustomClass; } } - (void)viewDidLoad { twitterObjects = [[NSMutableArray alloc]init]; [super viewDidLoad]; [self twitterAPIcall]; // Do any additional setup after loading the view, typically from a nib. } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 100; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; // initiate celli CustomCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; // add objects to cell if (cell != nil) { //TwitterCustomObject *newCustomClass = [twitterObjects objectAtIndex:indexPath.row]; //[cell refreshCell:newCustomClass.userName userImage:newCustomClass.userImage]; [cell refreshCell:@"Brian" userImage:[UIImage imageNamed:@"love.jpg"]]; } return cell; } -(void)twitterAPIcall { //create an instance of the account store from account frameworks ACAccountStore *accountStore = [[ACAccountStore alloc]init]; // make sure we have a valid object if (accountStore != nil) { // get the account type ex: Twitter, FAcebook info ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; // make sure we have a valid object if (accountType != nil) { // give access to the account iformation [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { if (granted) { //^^^success user gave access to account information // get the info of accounts NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType]; // make sure we have a valid object if (twitterAccounts != nil) { //NSLog(@"Accounts: %@",twitterAccounts); // get the current account information ACAccount *currentAccount = [twitterAccounts objectAtIndex:0]; // make sure we have a valid object if (currentAccount != nil) { //string from twitter api NSString *requestString = @"https://api.twitter.com/1.1/friends/list.json"; // request the data from the request screen call SLRequest *myRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:requestString] parameters:nil]; // must authenticate request [myRequest setAccount:currentAccount]; // perform the request named myRequest [myRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { // check to make sure there are no errors and we have a good http:request of 200 if ((error == nil) && ([urlResponse statusCode] == 200)) { // make array of dictionaries from the twitter api data using NSJSONSerialization NSArray *twitterFeed = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil]; NSMutableArray *nameArray = [twitterFeed valueForKeyPath:@"users"]; // for loop that loops through all the post for (NSInteger i =0; i<[twitterFeed count]; i++) { NSString *nameString = [nameArray valueForKeyPath:@"name"]; NSString *imageString = [nameArray valueForKeyPath:@"profile_image_url"]; NSLog(@"Name feed: %@",nameString); NSLog(@"Image feed: %@",imageString); // get data into my mutable array TwitterCustomObject *twitterInfo = [self createPostFromArray:[nameArray objectAtIndex:i]]; //NSLog(@"Image feed: %@",twitterInfo); if (twitterInfo != nil) { [twitterObjects addObject:twitterInfo]; } } } }]; } } } else { // the user didn't give access UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"This app will only work with twitter accounts being allowed!." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:FALSE]; } }]; } } } -(TwitterCustomObject*)createPostFromArray:(NSArray*)postArray { // create strings to catch the data in NSArray *userArray = [postArray valueForKeyPath:@"users"]; NSString *myUserName = [userArray valueForKeyPath:@"name"]; NSString *twitImageURL = [userArray valueForKeyPath:@"profile_image_url"]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:twitImageURL]]]; // initiate object to put the data in TwitterCustomObject *twitterData = [[TwitterCustomObject alloc]initWithPostInfo:myUserName myImage:image]; NSLog(@"Name: %@",myUserName); return twitterData; } -(IBAction)done:(UIStoryboardSegue*)segue { } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Here is my customObject class TwitterCustomClass.h // // TwitterCustomObject.h // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import <Foundation/Foundation.h> @interface TwitterCustomObject : NSObject { } @property (nonatomic, readonly) NSString *userName; @property (nonatomic, readonly) UIImage *userImage; -(id)initWithPostInfo:(NSString*)screenName myImage:(UIImage*)myImage; @end TwitterCustomClass.m // // TwitterCustomObject.m // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import "TwitterCustomObject.h" @implementation TwitterCustomObject -(id)initWithPostInfo:(NSString*)screenName myImage:(UIImage*)myImage { // initialize as object if (self = [super init]) { // use the data to be passed back and forth to the tableview _userName = [screenName copy]; _userImage = [myImage copy]; } return self; } @end The problem is I get the values in the method twitterAPIcall, I can get the names and image values or strings from the values. But in the (TwitterCustomObject*)createPostFromArray:(NSArray*)postArray method all values are coming up as null.I thought it got added with this line of code in the twitterAPIcall method [twitterObjects addObject:twitterInfo];?

    Read the article

  • Memory Leaks - Objective-C

    - by reising1
    Can anyone help point out memory leaks? I'm getting a bunch within this method and I'm not sure exactly how to fix it. - (NSMutableArray *)getTop5AndOtherKeysAndValuesFromDictionary:(NSMutableDictionary *)dict { NSLog(@"get top 5"); int sumOfAllValues = 0; NSMutableArray *arr = [[[NSMutableArray alloc] init] retain]; for(NSString *key in dict){ NSString *value = [[dict objectForKey:key] retain]; [arr addObject:value]; sumOfAllValues += [value intValue]; } //sort values NSArray *sorted = [[arr sortedArrayUsingFunction:sort context:NULL] retain]; [arr release]; //top 5 values int sumOfTop5 = 0; NSMutableArray *top5 = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < 5; i++) { int proposedIndex = [sorted count] - 1 - i; if(proposedIndex >= 0) { [top5 addObject:[sorted objectAtIndex:([sorted count] - i - 1)]]; sumOfTop5 += [[sorted objectAtIndex:([sorted count] - i - 1)] intValue]; } } [sorted release]; //copy of all keys NSMutableArray *copyOfKeys = [[[NSMutableArray alloc] init] retain]; for(NSString *key in dict) { [copyOfKeys addObject:key]; } //copy of top 5 values NSMutableArray *copyOfTop5 = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < [top5 count]; i++) { [copyOfTop5 addObject:[top5 objectAtIndex:i]]; } //get keys with top 5 values NSMutableArray *outputKeys = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < [top5 count]; i++) { NSString *targetValue = [top5 objectAtIndex:i]; for(int j = 0; j < [copyOfKeys count]; j++) { NSString *key = [copyOfKeys objectAtIndex:j]; NSString *val = [dict objectForKey:key]; if([val isEqualToString:targetValue]) { [outputKeys addObject:key]; [copyOfKeys removeObjectAtIndex:j]; break; } } } [outputKeys addObject:@"Other"]; [top5 addObject:[[NSString stringWithFormat:@"%d",(sumOfAllValues - sumOfTop5)] retain]]; NSMutableArray *output = [[NSMutableArray alloc] init]; [output addObject:outputKeys]; [output addObject:top5]; NSMutableArray *percents = [[NSMutableArray alloc] init]; int sum = sumOfAllValues; float leftOverSum = sum * 1.0f; int count = [top5 count]; float val1, val2, val3, val4, val5; if(count >= 1) val1 = ([[top5 objectAtIndex:0] intValue] * 1.0f)/sum; else val1 = 0.0f; if(count >=2) val2 = ([[top5 objectAtIndex:1] intValue] * 1.0f)/sum; else val2 = 0.0f; if(count >= 3) val3 = ([[top5 objectAtIndex:2] intValue] * 1.0f)/sum; else val3 = 0.0f; if(count >= 4) val4 = ([[top5 objectAtIndex:3] intValue] * 1.0f)/sum; else val4 = 0.0f; if(count >=5) val5 = ([[top5 objectAtIndex:4] intValue] * 1.0f)/sum; else val5 = 0.0f; if(val1 >= .00001f) { NSMutableArray *a1 = [[NSMutableArray alloc] init]; [a1 addObject:[outputKeys objectAtIndex:0]]; [a1 addObject:[top5 objectAtIndex:0]]; [a1 addObject:[NSString stringWithFormat:@"%.01f",(val1*100)]]; [percents addObject:a1]; leftOverSum -= ([[top5 objectAtIndex:0] intValue] * 1.0f); } if(val2 >= .00001f) { NSMutableArray *a2 = [[NSMutableArray alloc] init]; [a2 addObject:[outputKeys objectAtIndex:1]]; [a2 addObject:[top5 objectAtIndex:1]]; [a2 addObject:[NSString stringWithFormat:@"%.01f",(val2*100)]]; [percents addObject:a2]; leftOverSum -= ([[top5 objectAtIndex:1] intValue] * 1.0f); } if(val3 >= .00001f) { NSMutableArray *a3 = [[NSMutableArray alloc] init]; [a3 addObject:[outputKeys objectAtIndex:2]]; [a3 addObject:[top5 objectAtIndex:2]]; [a3 addObject:[NSString stringWithFormat:@"%.01f",(val3*100)]]; [percents addObject:a3]; leftOverSum -= ([[top5 objectAtIndex:2] intValue] * 1.0f); } if(val4 >= .00001f) { NSMutableArray *a4 = [[NSMutableArray alloc] init]; [a4 addObject:[outputKeys objectAtIndex:3]]; [a4 addObject:[top5 objectAtIndex:3]]; [a4 addObject:[NSString stringWithFormat:@"%.01f",(val4*100)]]; [percents addObject:a4]; leftOverSum -= ([[top5 objectAtIndex:3] intValue] * 1.0f); } if(val5 >= .00001f) { NSMutableArray *a5 = [[NSMutableArray alloc] init]; [a5 addObject:[outputKeys objectAtIndex:4]]; [a5 addObject:[top5 objectAtIndex:4]]; [a5 addObject:[NSString stringWithFormat:@"%.01f",(val5*100)]]; [percents addObject:a5]; leftOverSum -= ([[top5 objectAtIndex:4] intValue] * 1.0f); } float valOther = (leftOverSum/sum); if(valOther >= .00001f) { NSMutableArray *a6 = [[NSMutableArray alloc] init]; [a6 addObject:[outputKeys objectAtIndex:5]]; [a6 addObject:[top5 objectAtIndex:5]]; [a6 addObject:[NSString stringWithFormat:@"%.01f",(valOther*100)]]; [percents addObject:a6]; } [output addObject:percents]; NSLog(@"mu - a"); //[arr release]; NSLog(@"mu - b"); //[copyOfKeys release]; NSLog(@"mu - c"); //[copyOfTop5 release]; NSLog(@"mu - c"); //[outputKeys release]; //[top5 release]; //[percents release]; return output; }

    Read the article

  • Why is the class wrong for NSFetchRequest?

    - by Stephen Furlani
    Hello, I am working with an undocumented API (Osirix) and I have a sister-question to the one I posted here. I am having trouble loading objects from a managed object context. With loading from API, using their instance of _context and _model 2010-05-28 14:05:13.588 OsiriX[44012:a0f] Entity: Study 2010-05-28 14:05:13.589 OsiriX[44012:a0f] EntityClassName: DicomStudy 2010-05-28 14:05:13.589 OsiriX[44012:a0f] ClassName: DicomStudy With loading from Fetch Request (and my own instance of _context, and _model) 2010-05-28 14:19:09.956 rcOsirix[44431:7a03] Entity: Study 2010-05-28 14:19:09.957 rcOsirix[44431:7a03] EntityClassName: DicomStudy 2010-05-28 14:19:09.958 rcOsirix[44431:7a03] ClassName: NSManagedObject output given by: NSLog(@"Entity: %@",[[item entity] name]); NSLog(@"EntityClassName: %@", [[item entity] managedObjectClassName]); NSLog(@"ClassName: %s", class_getName(object_getClass([item class]))); So it is obvious that even though the Entity thinks it is a DicomSeries - it is not. It is just a NSManagedObject. DicomSeries has some "hard-coded" KVC stuff that I ran into a problem with in my other question. I'm pursuing a different line of reasoning in this thread - with the loading of the objects. The following is their code: - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel) return managedObjectModel; NSMutableSet *allBundles = [[NSMutableSet alloc] init]; [allBundles addObject: [NSBundle mainBundle]]; [allBundles addObjectsFromArray: [NSBundle allFrameworks]]; managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: [NSURL fileURLWithPath: [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/OsiriXDB_DataModel.mom"]]]; [allBundles release]; return managedObjectModel; } - (NSManagedObjectContext *) managedObjectContextLoadIfNecessary:(BOOL) loadIfNecessary { NSError *error = nil; NSString *localizedDescription; NSFileManager *fileManager; if( currentDatabasePath == nil) return nil; if (managedObjectContext) return managedObjectContext; if( loadIfNecessary == NO) return nil; fileManager = [NSFileManager defaultManager]; [persistentStoreCoordinator release]; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: self.managedObjectModel]; managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator: persistentStoreCoordinator]; NSURL *url = [NSURL fileURLWithPath: currentDatabasePath]; if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) { NSLog(@"********** managedObjectContextLoadIfNecessary FAILED: %@", error); localizedDescription = [error localizedDescription]; error = [NSError errorWithDomain:@"OsiriXDomain" code:0 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:error, NSUnderlyingErrorKey, [NSString stringWithFormat:@"Store Configuration Failure: %@", ((localizedDescription != nil) ? localizedDescription : @"Unknown Error")], NSLocalizedDescriptionKey, nil]]; } [[managedObjectContext undoManager] setLevelsOfUndo: 1]; [[managedObjectContext undoManager] disableUndoRegistration]; // This line is very important, if there is NO database.sql file [self saveDatabase: currentDatabasePath]; return managedObjectContext; } This is my code: NSManagedObjectModel* DataModule::managedObjectModel() { if (_managedObjectModel) return _managedObjectModel; NSMutableSet *allBundles = [[NSMutableSet alloc] init]; [allBundles addObject: [NSBundle mainBundle]]; [allBundles addObjectsFromArray: [NSBundle allFrameworks]]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: [NSURL fileURLWithPath: [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/OsiriXDB_DataModel.mom"]]]; [allBundles release]; return [_managedObjectModel retain]; } ... NSError *error = nil; [_storeCoordinator release]; _storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel()]; _context = [[NSManagedObjectContext alloc] init]; [_context setPersistentStoreCoordinator: _storeCoordinator]; NSURL *url = [NSURL fileURLWithPath: [[NSString alloc] initWithCString:_DBPath.c_str()]]; if (url == nil) { [pool release]; _loadLock = false; return nil; } if (![_storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) { NSLog(@"********** managedObjectContextLoadIfNecessary FAILED: %@", error); NSString *localizedDescription = [error localizedDescription]; error = [NSError errorWithDomain:@"OsiriXDomain" code:0 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:error, NSUnderlyingErrorKey, [NSString stringWithFormat:@"Store Configuration Failure: %@", ((localizedDescription != nil) ? localizedDescription : @"Unknown Error")], NSLocalizedDescriptionKey, nil]]; //Exit Failure [pool release]; _loadLock = false; return nil; } [[_context undoManager] setLevelsOfUndo: 1]; [[_context undoManager] disableUndoRegistration]; ... I am including all the same frameworks.... but _allBundles isn't even used to create the managedObjectModel so I don't know what it's supposed to do except load them into memory so that the mom can look at them while loading. Totally lost. Help! Why would objects returned by my FetchRequest with the same Entity come out as NSManagedObjects and not DicomStudys? I'm including DicomStudy.h so it should see the object during creation of the model, context, and fetch request. [request setEntity: [[managedObjectModel() entitiesByName] objectForKey:@"Study"]]; Thanks in advance, -Stephen

    Read the article

  • keyDown works but i get beeps

    - by Oscar
    I just got my keydown method to work. But i get system beep everytime i press key. i have no idea whats wrong. Googled for hours and all people say is that if you have your keyDown method you should also implement the acceptsFirstResponder. did that to and it still doesn't work. #import <Cocoa/Cocoa.h> #import "PaddleView.h" #import "BallView.h" @interface GameController : NSView { PaddleView *leftPaddle; PaddleView *rightPaddle; BallView * ball; CGPoint ballVelocity; int gameState; int player1Score; int player2Score; } @property (retain) IBOutlet PaddleView *leftPaddle; @property (retain) IBOutlet PaddleView *rightPaddle; @property (retain) IBOutlet BallView *ball; - (void)reset:(BOOL)newGame; @end #import "GameController.h" #define GameStateRunning 1 #define GameStatePause 2 #define BallSpeedX 0.2 #define BallSpeedY 0.3 #define CompMoveSpeed 15 #define ScoreToWin 5 @implementation GameController @synthesize leftPaddle, rightPaddle, ball; - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if(self) { gameState = GameStatePause; ballVelocity = CGPointMake(BallSpeedX, BallSpeedY); [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; } return self; } - (void)gameLoop { if(gameState == GameStateRunning) { [ball setFrameOrigin:CGPointMake(ball.frame.origin.x + ballVelocity.x, ball.frame.origin.y + ballVelocity.y)]; if(ball.frame.origin.x + 15 > self.frame.size.width || ball.frame.origin.x < 0) { ballVelocity.x =- ballVelocity.x; } if(ball.frame.origin.y + 35 > self.frame.size.height || ball.frame.origin.y < 0) { ballVelocity.y =- ballVelocity.y; } } if(CGRectIntersectsRect(ball.frame, leftPaddle.frame)) { if(ball.frame.origin.x > leftPaddle.frame.origin.x) { ballVelocity.x =- ballVelocity.x; } } if(CGRectIntersectsRect(ball.frame, rightPaddle.frame)) { if(ball.frame.origin.x +15 > rightPaddle.frame.origin.x) { ballVelocity.x =- ballVelocity.x; } } if(ball.frame.origin.x <= self.frame.size.width / 2) { if(ball.frame.origin.y < leftPaddle.frame.origin.y + 75 && leftPaddle.frame.origin.y > 0) { [leftPaddle setFrameOrigin:CGPointMake(leftPaddle.frame.origin.x, leftPaddle.frame.origin.y - CompMoveSpeed)]; } if(ball.frame.origin.y > leftPaddle.frame.origin.y +75 && leftPaddle.frame.origin.y < 700 - leftPaddle.frame.size.height ) { [leftPaddle setFrameOrigin:CGPointMake(leftPaddle.frame.origin.x, leftPaddle.frame.origin.y + CompMoveSpeed)]; } } if(ball.frame.origin.x <= 0) { player2Score++; [self reset:(player2Score >= ScoreToWin)]; } if(ball.frame.origin.x + 15 > self.frame.size.width) { player1Score++; [self reset:(player1Score >= ScoreToWin)]; } } - (void)reset:(BOOL)newGame { gameState = GameStatePause; [ball setFrameOrigin:CGPointMake((self.frame.size.width + 7.5) / 2, (self.frame.size.height + 7.5)/2)]; if(newGame) { if(player1Score > player2Score) { NSLog(@"Player 1 Wins!"); } else { NSLog(@"Player 2 Wins!"); } player1Score = 0; player2Score = 0; } else { NSLog(@"Press key to serve"); } NSLog(@"Player 1: %d",player1Score); NSLog(@"Player 2: %d",player2Score); } - (void)moveRightPaddleUp { if(rightPaddle.frame.origin.y < 700 - rightPaddle.frame.size.height) { [rightPaddle setFrameOrigin:CGPointMake(rightPaddle.frame.origin.x, rightPaddle.frame.origin.y + 20)]; } } - (void)moveRightPaddleDown { if(rightPaddle.frame.origin.y > 0) { [rightPaddle setFrameOrigin:CGPointMake(rightPaddle.frame.origin.x, rightPaddle.frame.origin.y - 20)]; } } - (BOOL)acceptsFirstResponder { return YES; } - (void)keyDown:(NSEvent *)theEvent { if ([theEvent modifierFlags] & NSNumericPadKeyMask) { NSString *theArrow = [theEvent charactersIgnoringModifiers]; unichar keyChar = 0; if ( [theArrow length] == 0 ) { return; // reject dead keys } if ( [theArrow length] == 1 ) { keyChar = [theArrow characterAtIndex:0]; if ( keyChar == NSLeftArrowFunctionKey ) { gameState = GameStateRunning; } if ( keyChar == NSRightArrowFunctionKey ) { } if ( keyChar == NSUpArrowFunctionKey ) { [self moveRightPaddleUp]; } if ( keyChar == NSDownArrowFunctionKey ) { [self moveRightPaddleDown]; } [super keyDown:theEvent]; } } else { [super keyDown:theEvent]; } } - (void)drawRect:(NSRect)dirtyRect { } - (void)dealloc { [ball release]; [rightPaddle release]; [leftPaddle release]; [super dealloc]; } @end

    Read the article

  • Parsing nested JSON objects with JSON Framework for Objective-C

    - by Sheehan Alam
    I have the following JSON object: { "response": { "status": 200 }, "messages": [ { "message": { "user": "value" "pass": "value", "url": "value" } ] } } I am using JSON-Framework (also tried JSON Touch) to parse through this and create a dictionary. I want to access the "message" block and pull out the "user", "pass" and "url" values. In Obj-C I have the following code: // Create new SBJSON parser object SBJSON *parser = [[SBJSON alloc] init]; // Prepare URL request to download statuses from Twitter NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; // Perform request and get JSON back as a NSData object NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // Get JSON as a NSString from NSData response NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //Print contents of json-string NSArray *statuses = [parser objectWithString:json_string error:nil]; NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]); NSLog(@"Array Count: %d", [statuses count]); NSDictionary *results = [json_string JSONValue]; NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"]; for (NSDictionary *tweet in tweets) { NSString *url = [tweet objectForKey:@"url"]; NSLog(@"url is: %@",url); } I can pull out "messages" and see all of the "message" blocks, but I am unable to parse deeper and pull out the "user", "pass", and "url".

    Read the article

  • Unable to load UIView with initWithNibName in Apple SDK 3.1.3

    - by James Foster
    I am trying to load my UIViewController and corresponding UIView programmatically in the AppDelegate class. I have the following in the applicationDidFinishLaunchingMethod of the AppDelegate class: (void)applicationDidFinishLaunching:(UIApplication *)application { NSLog(@"--- AppDelegate applicationDidFinishLaunching Start"); // Override point for customization after application launch //MainController *controller = [[MainController alloc] initWithNibName:@"MainView" bundle:nil]; MainController2 *controller = [[MainController2 alloc] initWithNibName:@"MainView2" bundle:nil]; if (controller.view == nil) { NSLog(@"--- controller view is nil!!!!!!"); } [window addSubview:controller.view]; [window makeKeyAndVisible]; NSLog(@"--- AppDelegate applicationDidFinishLaunching End"); } Basically the view in the viewController doesn't load and when the application launches, it just shows the blank window. What is funny is that it worked before and then just stopped working. I am wondering if this is a bug in iPhone SDK 3.1.3??? This is a really annoying issue, and I was quite a ways along in a new project when I started having this problem and had to start over with a blank project and copy over all of my resources, when it started happening again... I have uninstalled iPhone OS 3.1.3 and reinstalled and the problem prevails... I also created a second UIViewController class and corresponding nib which DOES LOAD just fine... I am not sure why one works and the other doesn't it... You can download a sample project which demonstrates this issue at the following link: http://www.mediafire.com/?nmhnmhbeyki To switch back and forth between the working/nonworking UIViewController and UIView simply comment comment/comment out the initWithNibLine lines in the AppDelegate and the corresponding #import "MainController.h" statements in the appdelegate.h file... Any ideas??? The sample project I have linked to isolates the problem in as few files/lines of code as possible... I appreciate any help you might be able to provide. Thanks, James

    Read the article

  • Objective-C SSL Synchronous Connection

    - by Mike
    Hello, I'm a little new to objective-C but have run across a problem that I can't solve, mostly because I'm not sure I am implementing the solution correctly. I am trying to connect using a Synchronous Connection to a https site with a self-signed certificate. I am getting the Error Domain=NSURLErrorDomain Code=-1202 "untrusted server certificate" Error that I have seen some solutions to on this forum. The solution i found was to add: - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; } (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; } to the NSURLDelegate to accept all certificates. When I connect to the site using just a: NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://examplesite.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; It works fine and I see the challenge being accepted. However when I try to connect using the synchronous connection I still get the error and I don't see the challenge functions being called when I put in logging. How can I get the synchronous connection to use the challenge methods? Is it something to do with the delegate:self part of the URLConnection? I also have logging for sending/receiving data within the NSURLDelegate that is called by my connection function but not by the synchronous function. What I am using for the synchronous part: NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:@"https://examplesite.com/"]]; [request setHTTPMethod: @"POST"]; [request setHTTPBody: [[NSString stringWithString:@"username=mike"] dataUsingEncoding: NSUTF8StringEncoding]]; dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"%@", error); stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding]; NSLog(@"%@", stringReply); [stringReply release]; NSLog(@"Done"); Like I mentioned I'm a little new to objective C so be kind :) Thanks for any help. Mike

    Read the article

  • IOs7 app crashing when in background

    - by Leonardo
    My app sometimes crashes when in background and shows the following crash log: Nov 7 12:33:31 iPad backboardd[29] <Warning>: MyApp[3096] has active assertions beyond permitted time: {( <BKProcessAssertion: 0x14680c60> identifier: Called by MyApp, from -[AppDelegate applicationDidEnterBackground:] process: MyApp[3096] permittedBackgroundDuration: 180.000000 reason: finishTask owner pid:3096 preventSuspend preventIdleSleep preventSuspendOnSleep )} Looking through other questions I found out that the crash message indicates that I didn't end a task properly, so when its time expired the OS ended it and crashed my app. So I added some NSLogs: - (void)applicationDidEnterBackground:(UIApplication *)application { [self saveContext]; [Settings setCallLock:YES]; [self saveStuff]; if ([self isBackgroundTaskNeeded]) { UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [self pauseDownloads]; NSLog(@"Debug - Ending background task %d",bgTask); [app endBackgroundTask:bgTask]; NSLog(@"Debug - Background task %d ended",bgTask); bgTask = UIBackgroundTaskInvalid; }]; NSLog(@"Debug - Starting background task %d",bgTask); [self initBackground]; } } and found out that the task was called twice when it crashed: Nov 7 12:30:02 iPad MyApp[3096] <Warning>: Debug - Starting background task 7 Nov 7 12:30:30 iPad MyApp[3096] <Warning>: Debug - Starting background task 8 Nov 7 12:33:26 iPad MyApp[3096] <Warning>: Debug - Ending background task 8 Nov 7 12:33:26 iPad MyApp[3096] <Warning>: Debug - Background task 8 ended Nov 7 12:33:26 iPad MyApp[3096] <Warning>: Debug - Ending background task 0 Nov 7 12:33:26 iPad MyApp[3096] <Warning>: Debug - Background task 0 ended I wasn't able to tell when the double call happens and why. So question is why is the task being called twice and is there a way to avoid it? Edit: - (void) pauseDownloads { for (AFDownloadRequestOperation *operation in self.operationQueue.operations) { if(![operation isPaused]) { [operation pause]; } } }

    Read the article

  • Calculating File size before download - Downloading NSURLConnection Slider timing

    - by sagar
    Ok ! Coming to the point directly. What I want to do is explained as follows. I have an url of MP3 file. ( for example Sound File ) Now, When user starts application. Download should start & for that I have implemented following methods. -(void)viewDidLoad { [super viewDidLoad]; NSURL *url=[NSURL URLWithString:@"http://xyz.pqr.com/abc.mp3"]; NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:120]; NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES]; if(con){ myWebData=[[NSMutableData data] retain]; } else { // [MainHandler performSelector:@selector(targetSelector:) withObject:nil]; } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@",@"connection established"); [myWebData setLength: 0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"%@",@"connection receiving data"); [myWebData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"%@",@"connection failed"); [connection release]; // [AlertViewHandler showAlertWithErrorMessage:@"Sorry, there is no network connection. Please check your network and try again."]; // [self parserDidEndDocument:nil]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; } Now, Above methods work perfectly for downloading. But missing points are as follows. I can not get the exact size which is going to be downloaded. ( means I want to know what is the size of file - which is going to be download )

    Read the article

  • Deserializing a complex JSON result (array of dictionaries) with TouchJSON

    - by jpm
    I did a few tests with TouchJSON last night and it worked pretty well in general for simple cases. I'm using the following code to read some JSON content from a file, and deserialize it: NSString *jsonString = [[NSString alloc] initWithContentsOfFile:@"data.json"]; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding]; NSError *error = nil; NSDictionary *items = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error]; NSLog(@"total items: %d", [items count]); NSLog(@"error: %@", [error localizedDescription]); That works fine if I have a very simple JSON object in the file (i.e. a dictionary): {"id": "54354", "name": "boohoo"} This way I was able to get access to the array of values, as I wanted to get the item based on its index within the list: NSArray *items_list = [items allValues]; NSString *name = [items_list objectAtIndex:1]; (I understand that I could have fetched the name with the dictionary API) Now I would like to deserialize a semi-complex JSON string, which represents an array of dictionaries. An example of such a JSON string is below: [{"id": "123456", "name": "touchjson"}, {"id": "3456", "name": "bleh"}] When I try to run the same code above against this new content in the data.json file, I don't get any results back. My NSLog() call says "total items: 0", and no error is coming back in the NSError object. Any clues on what is going on? I'm completely lost on what to do, as there isn't much documentation available for TouchJSON, and much less usage examples.

    Read the article

  • UIAlertView -show causing a memory leak

    - by Erik
    I'm relatively new to iPhone Development, so this may be my fault, but it goes against what I've seen. :) I think that I'm creating a UIAlertView that lives just in this vaccuum of the 'if' statement. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if(!data) { // Add an alert UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Unable to contact server" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; NSLog(@"retain count before show: %i", alert.retainCount); [alert show]; NSLog(@"retain count before release: %i", alert.retainCount); [alert release]; NSLog(@"retain count after release: %i", alert.retainCount); return nil; } However, the console logs baffle me. retain count before show: 1 retain count before release: 6 retain count after release: 5 I've tried also adding: alert = nil; after the release. That makes the retain count 0, but I still show a leak. And if it helps, the leak's Responsible Frame is UIKeyboardInputManagerClassForInputMode. I'm also using OS 4 Beta 3. So anyone have any ideas how a local UIAlertView's retain count would increment itself by 5 when calling -show? Thanks for your help!

    Read the article

  • NSFileManager works fine on simulator but not on device

    - by Jenicek
    Hi, I have problem creating directories and files with NSFileManager on the iPhone device. My code, shown below, works fine on the simulator, but not on the device, could you please help me? Gimme some directions where the problem may be, thanks for every reply.. I'm first creating directories this way: NSFileManager *fileMgr = [NSFileManager defaultManager]; NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES); NSString *appPath = [[NSString alloc] init]; appPath = [arPaths objectAtIndex:0]; strDownloadsDir = [[NSString alloc] init]; strDownloadsDir = [[appPath stringByAppendingPathComponent:@"/Other"] copy]; if(![fileMgr fileExistsAtPath:strDownloadsDir]) [fileMgr createDirectoryAtPath:strDownloadsDir attributes:nil]; and then I'm trying to create new file in this directory this way: NSString *filePath = [strDownloadsDir stringByAppendingPathComponent:strDlFileName]; //Test whether this file exists, if not, create it NSLog(@"%@", filePath); if(![fileMgr fileExistsAtPath:filePath]) { if([fileMgr createFileAtPath:filePath contents:nil attributes:nil]) NSLog(@"Creating new file at path %@", filePath); else NSLog(@"Failed to create new file."); } It seems that there's something wrong with whole NSFileManager, because when I'm using fileExistAtPath with a path given by this NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES); NSString *appPath = [[NSString alloc] init]; appPath = [arPaths objectAtIndex:0]; it is not working too, I tried to change directory to NSDocumentsDirectory but it did not help

    Read the article

  • Generate JSON object with transactionReceipt

    - by Carlos
    Hi, I've been the past days trying to test my first in-app purchse iphone application. Unfortunately I can't find the way to talk to iTunes server to verify the transactionReceipt. Because it's my first try with this technology I chose to verify the receipt directly from the iPhone instead using server support. But after trying to send the POST request with a JSON onbject created using the JSON api from google code, itunes always returns a strange response (instead the "status = 0" string I wait for). Here's the code that I use to verify the receipt: - (void)recordTransaction:(SKPaymentTransaction *)transaction { NSString *receiptStr = [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding]; NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"algo mas",@"receipt-data",nil]; NSString *jsonString = [jsonDictionary JSONRepresentation]; NSLog(@"string to send: %@",jsonString); NSLog(@"JSON Created"); urlData = [[NSMutableData data] retain]; //NSURL *sandboxStoreURL = [[NSURL alloc] initWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; NSLog(@"will create connection"); [[NSURLConnection alloc] initWithRequest:request delegate:self]; } maybe I'm forgetting something in the request's headers but I think that the problem is in the method I use to create the JSON object. HEre's how the JSON object looks like before I add it to the HTTPBody : string to send: {"receipt-data":"{\n\t\"signature\" = \"AUYMbhY ........... D0gIjEuMCI7Cn0=\";\n\t\"pod\" = \"100\";\n\t\"signing-status\" = \"0\";\n}"} The responses I've got: complete response { exception = "java.lang.IllegalArgumentException: Property list parsing failed while attempting to read unquoted string. No allowable characters were found. At line number: 1, column: 0."; status = 21002; } Thanks a lot for your guidance.

    Read the article

  • [NSLocale currentLocale] always returns "en_US" not user's current language

    - by Prairiedogg
    I'm in the processes of internationalizing an iPhone app - I need to make programmatic changes to certain views based on what the user's current locale is. I'm going nuts because no matter what the language preference on the iPhone simulator or actual hardware are, locale always evaluates to "en_US": NSString *locale = [[NSLocale currentLocale] localeIdentifier]; NSLog(@"current locale: %@", locale); The crazy thing is that the rest of the application behaves as expected. The correct strings are selected from the Localization.strings file and used in the interface, and the correct .xib files for the selected locale are used. I have also tried the following, to no avail and with the same result: NSString *locale = [[NSLocale autoupdatingCurrentLocale] localeIdentifier]; NSLog(@"current locale: %@", locale); Is there something simple I'm missing? A preference or an import perhaps? Update: As Darren's answer suggests, the preference I'm looking for is not in NSLocale, rather it is here: NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; NSArray* languages = [defs objectForKey:@"AppleLanguages"]; NSString* preferredLang = [languages objectAtIndex:0]; NSLog(@"preferredLang: %@", preferredLang);

    Read the article

  • Can get coordinates from iPhone simulator, but can't get coordinates from iPhone device

    - by iPhoneARguy
    Hi everyone, I've run into something of a mysterious bug (to me). I have some code to pick out the user's current location on the iPhone SDK. It works fine on the iPhone simulator, but when I try to run it on the actual device, I get a weird error. Here is the code (I am using ASIFormDataRequest to create a POST request): ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:@"testauthor" forKey:@"author"]; [request setPostValue:[[NSNumber numberWithDouble:datum.location.coordinate.latitude] stringValue] forKey:@"latitude"]; NSLog(@"%f", datum.location.coordinate.latitude); NSLog(@"%f", datum.location.coordinate.longitude); [request setPostValue:[[NSNumber numberWithDouble:datum.location.coordinate.longitude] stringValue] forKey:@"longitude"]; [request setPostValue:datum.comment forKey:@"comment"]; On the simulator, NSLog does log both the latitude and longitude, but on the iPhone, it does not. Even stranger, when I go through with the debugger on the device, I try "po datum.location", I get <+###, -###> +/- 223.10m (speed 0.00 mps / course -1.00) @ 2010-05-02 22:18:37 -0400 (### replaced by my location) but when I do "(gdb) po datum.location.coordinate" I get: There is no member named coordinate. Do you guys have any idea why this might happen? Thanks in advance for your help!

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >