mardi 5 mai 2015

Draw the contents of an array modified in the background

I have a background thread that runs and modifies the contents of a NSMutableArray within an object. This takes a long time to run (several hours) and I periodically want to draw the contents of an array within the drawRect of a NSView to check on progress and see the intermediate results.

My object has a protocol with a method called: didChange:

// How I start my background thread
[self performSelectorInBackground:@selector(startProcessing) withObject:nil];

- (void)startProcessing {
    myObject.delegate = self;
    [myObject start];
}

// My protocol implementation
- (void)myObjectDidChange:(myObjectClass *)sender {
    [myView setNeedsDisplay:YES];
}

// My View's drawRect (pseudo code)
- (void)drawRect {
    [myObject drawInContext:context];
}

All works, except that the NSMutableArray backing all this is being changed whilst the drawing takes place. How should I do this? Do I somehow pause the processing in the background thread whilst the update is taking place?

EDIT: This is the sort of display I am drawing (although much more complicated):

enter image description here

Any help appreciated.

Objective C forward declaration and type compatibility

I have code like following:

#import<ViewModelBase.h>

@interface ViewControllerA : UIViewController
@property (nonatomic, strong) ViewModelBase* viewModel;
@end

Then I need to do something like following:

#import<ViewControllerA.h>

@class ViewModelSubclass;

@interface ViewControllerB : ViewControllerA
@property (nonatomic, strong) ViewModelSubclass* viewModel;
@end

Where ViewModelSubclass.h is not supposed to be imported to ViewControllerB.h, only to .m file. However, ViewModelSubclass is supposed to be subclass of ViewModelBase. This is done to hide interface of ViewModelSubclass from clients of ViewControllerB. How do I solve "Property type 'ViewModelSubclass*' is incompatible with type 'ViewModelBAse*' inherited from ViewControllerA" warning? Or what is a better way to do it?

Place custom alert view in IOS

I want to achieve following custom alert view what is the best way to do it. rather then using addSubview I want to use some thing better
I previously use following but i want to use some thing better now

[self.view addSubview:NotConnected.view];

 [self.view removeFromSuperview];

enter image description here

ios objective c, iphone app works fine in iphone(all model), but crashes only in ipad device and ipad simulator

2015-05-06 11:36:18.414 Myproject[165:60b] *** -[UIViewAnimationState release]: message sent to deallocated instance 0x196b0820

And

EXC_BREAKPOINT(code=EXC_ARM_BREAKPOINT,subcode=Oxdefe)

This crash does not come in iphone(works fine in all iphone model), comes only in ipad, Please help me. Thank you.

UISegmentedControl segment order issue

i'm using the following code to set the color of each segment in UISegmentedControl.

for (int i = 0; i < [self.controlStatus numberOfSegments]; i++)
    {
        NSArray *ar=self.controlStatus.subviews;

        if ([[self.controlStatus titleForSegmentAtIndex:i] isEqualToString:@"ON"])
        {
            [[self.controlStatus.subviews objectAtIndex:i] setTintColor:[UIColor greenColor]];
        }
        else if ([[self.controlStatus titleForSegmentAtIndex:i] isEqualToString:@"OFF"])
        {
            [[self.controlStatus.subviews objectAtIndex:i] setTintColor:[UIColor orangeColor]];
        }
        else if ([[self.controlStatus titleForSegmentAtIndex:i] isEqualToString:@"HIDE"])
        {
            [[self.controlStatus.subviews objectAtIndex:i] setTintColor:[UIColor redColor]];
        }
        }
    }

But i'm not getting the color as i need in corresponding segment. Sometimes the colors are as follows:
1st segment - GREEN
2nd segment - ORANGE
3rd segment - RED

But at some stage when i navigate to other pages and come back, the color changes:
1st segment - RED
2nd segment - ORANGE
3rd segment - GREEN

Can anyone give me an idea about whats happening here.

Confusion over how I should use weakSelf in blocks

I have a lot of blocks in my code. I have a process for initialising a user upon login, I am using Parse.com as my backend:

PFQuery *messageBankQuery = [PFQuery queryWithClassName:@"messageBank"];
        [messageBankQuery whereKey:@"username" equalTo:[PFUser currentUser].username];
        [messageBankQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {


            if(!error){

                [self setupUserWithMessageBank:object];

            }//end no error if


            else{

                NSLog:(@"error");

           }

}];

The messageBank is a parse object that holds references to all the messages the user has. If that object is found setupUserWithMessageBank is called in the block. setupUserWithMessageBank also does more block work:

-(void)setupUserWithMessageBank: (PFObject *)object{


    __weak FriendsViewController *weakSelf = self;

    //2.)Init the user
    weakSelf.currentUser = [[appUser alloc] initWithParseUser:[PFUser currentUser] andMessageBank:object];

    //3.) Setup that message array
    [weakSelf.currentUser setupMessagedTodayWithHandler:^(BOOL successful) {

        if(successful){


            //4.)Add friends to the array
            [weakSelf.currentUser populateFriendsArrayWithCompletionHandler:^(BOOL successful, NSError *error, BOOL addSelf, BOOL alreadyFriends) {

                if(successful){

                    [self.indicator stopAnimating];
                    [self.indicator removeFromSuperview];
                    [self.tableView reloadData];

                    __weak FriendsViewController *weakSelf = self;
                    [weakSelf.currentUser refreshMessagesArrayWithCompletionHandler:^(BOOL successful, BOOL newMessages) {

                        if(successful) {


                            //set the button
                            [self.navigationItem.rightBarButtonItem setAction:@selector(showMessages)];

                        }

                        else{

                            [weakSelf displayGeneralError];
                        }


                    }];//end fill messages



                }

                else{

                    [weakSelf displayGeneralError];

                }



            }];//end populate method call




        }

        else{

            [weakSelf displayGeneralError];

        }
    }];




}

I am a little confused over the use of weakSelf. Is it okay to declare weakSelf inside the start of the setupUserWithMessageBank method? Because his method is called inside another block so technically it's being created inside a block. Do I need to pass weakSelf inside the method instead?

I'm also not completely sure where I should be using weakSelf. Do I need to use it to turn off activity indicators ? Any pointers about my usage of this would be really appreciated. Thanks!

Is it possible to get location within iOS framework?

I have created a framework in swift. But I am trying to get location values - lat and lon within the framework. The below code compiles fine but the location values are not getting populated. I have already added NSlocationWheninUseUSageDescription key to the info.plist.

Can some tell me is it even possible to get location values within the framework? If yes, then what should be done here?

import Foundation
import CoreLocation


public class FrameworkInit : NSObject, CLLocationManagerDelegate {


var locationManager = CLLocationManager()
var lat = ""
var long = ""
var locflag = false
var _appKey = ""

func fetchLocation()
{
    println("fetch loc called....")
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

public func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    var locValue:CLLocationCoordinate2D = manager.location.coordinate
    lat = locValue.latitude.description
    long = locValue.longitude.description
    println("lat.....\(lat)   \nlong...... \(long)")
    self.locationManager.stopUpdatingLocation()
    if !locflag {

        SPDeviceRegister().saveDataOnDevice(_appKey, lat: lat, long: long)

        SPReceiver().thresholdValueSetter()

    }
    locflag = true
}

 public func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("Error:" + error.localizedDescription)
    if !locflag {

        SPDeviceRegister().saveDataOnDevice(_appKey, lat: "0.0", long: "0.0")

        SPReceiver().thresholdValueSetter()
    }
    locflag = true
}


public init(appKey: String)
{
    super.init()
    _appKey = appKey
    self.fetchLocation()
}
}

My popover view controller dissapears when NSStatusBar IconView image changes.

I have a status bar app which shows a green circle in the status bar and alternates to a red circle every 10 seconds. It does this by using item.view = icon1; and item.view = icon2; to change the image. Initialised like this:

let item = NSStatusBar.systemStatusBar().statusItemWithLength(-1);
self.icon1 = IconView(imageName: "icon1", item: item);
self.icon2 = IconView(imageName: "icon2", item: item);

When you click on the green or red circle, a popover view with some settings I have made appears fine.

The problem is at each 10 second interval when the item.view changes to either the red or the green, the popover view closes and requires the user to click the green or red button again to show it.

How can I make the popover persist though status bar image changes and only disappear once the user clicks the red or green button again?

Here is my awakeFromNib() for the popover view:

override func awakeFromNib()
{
    let edge = NSMinYEdge
    let icon = self.icon
    let icon2 = self.icon2
    let icon3 = self.icon3

    let rect = icon.frame
    let rect2 = icon2.frame
    let rect3 = icon3.frame


    icon.onMouseDown = {
        if (icon.isSelected)
        {
            self.popover?.showRelativeToRect(rect, ofView: icon, preferredEdge: edge);
            return
        }

        self.popover?.close()
    }

    icon2.onMouseDown = {
        if (icon2.isSelected)
        {
            self.popover?.showRelativeToRect(rect2, ofView: icon2, preferredEdge: edge);
            return
        }

        self.popover?.close()
    }

    icon3.onMouseDown = {
        if (icon3.isSelected)
        {
            self.popover?.showRelativeToRect(rect3, ofView: icon3, preferredEdge: edge);
            return
        }

        self.popover?.close()
    }



}

}

How to search something in NSMutableDictionary

Hello I have a NSMutableArray like this

Contactarray (

{

   "firstNAme"="name1"
   "lastName"="name2"
   "phoneNumber"="12345678902";
}

{

   "firstNAme"="name1"
   "lastName"="name2"
   "phoneNumber"="12345678902";
}

I want to search the person when I type the person name in my UITextField. Then the filtered UItableView should be loaded. This NSMutableArray contains NSMutableDictionaries.

How can I find the matching object from these objects?

Lets say I want to search all name1 people. Then I want to find all the objects containing "name1" and those objects should fill to another array to load the UITableview

Please help me. Thanks.

Update height constraint programatically

I am new in auto layout. I have done all of my project from xib file, but now I faced a problem where I have to update an view's height programatically. I have tried below but now working.

[[self view] addConstraint:[NSLayoutConstraint constraintWithItem:loginContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:loginFrame.size.height]];

In console it's shows

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>",
    "<NSLayoutConstraint:0x787da210 V:[UIView:0x790cdfb0(400)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Authenticating in the background without authorizing the app for Instagram

I am trying to authenticate a user using his instagram credentials without having the user to authorize the app (authorization screen the instagram shows). I have already gone through Instagram API, but i couldn`t find a way to do that. And the endpoint i am trying to access(relationship) needs approval from instagram.

http://ift.tt/1DRFCkE

Modify the relationship between the current user and the target user.

REQUIREMENTS Scope: relationships To request access to this endpoint, please complete this form. PARAMETERS ACCESS_TOKEN A valid access token. ACTION One of follow/unfollow/block/unblock/approve/ignore.

But then i came across this application that does exactly that.

http://ift.tt/1dMfC5s

How can we split a complex string

<PrintLetterBarcodeData uid="229636134720" name="Nandan Mohan Nilekani" gender="M" yob="1955" house="856, 13th Main , 3rd Block" loc="Koramangala" vtc="Bangalore South" po="Koramangala" dist="Bangalore" state="Karnataka" pc="560034"/>

I want to split the above string to as

uid="229636134720"

name="Nandan Mohan Nilekani"

gender="M"

yob="1955"

house="856, 13th Main , 3rd Block"

loc="Koramangala"

vtc="Bangalore South"

po="Koramangala"

dist="Bangalore"

state="Karnataka"

pc="560034"

And i tried and failed to do like that

IOS Submit app to AppStore

I have a question! I had written a application in IOS, but I had met a problem when I submit my application to AppStore.

"-From Apple: On launch and content download, your app stores 252.95MB, which does not comply with the iOS Data Storage Guidelines."

How can I solve it?

Is it possible to convert a CABasicAnimation to [UIView animatewithDuration...?

I want to get the following code

CABasicAnimation *myAni = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
myAni.duration = 2.0f;
myAni.fromValue = [NSNumber numberWithFloat:1.0];
myAni.toValue = [NSNumber numberWithFloat:2.0];

[self.myView addAnimation:scaleAnimation forKey:@"myKey"];

to be in [UIView animateWithDuration.... (Instead of CABasicAnimation, I want it in animationWithDuration in the animations block.)

Is this possible? If so, how?

[UIView animateWithDuration:0.5
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     //I need it here
                 } 
                 completion:^(BOOL finished){

                 }];

IOS distribution certificate is grayout

My app is completed and now i want to distribute in apple app store but ios distribution option is grayout , if i delete a previous distribution certificate then is there any problem in my app which is on appstore

How to align custom UINavigationBar title (UILabel )in middle (iOS)

I am using following code to align 2 strings in UINavigationBar centre .

for ex:

         <Back     John Kelly Maria
                       23/F

I need these kind of middle aligned text in UINavigationbar but what jam now getting is all the text aligned in right side of UINavigationBar . something like this

      <Back                  John Kelly Maria   
                                  23/F

Please help..me . this is my code

 UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,50)];

    UIFont * customFont = [UIFont fontWithName:@"Helvetica Neue" size:19]; //custom font
    NSString * text =title;
    UILabel *patientNameLabel;
    if([title length]>15){
        patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];
    }else{
        patientNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,320,30)];

    }
    patientNameLabel.text = text;
    patientNameLabel.font = customFont;
    patientNameLabel.numberOfLines = 0;
    patientNameLabel.textAlignment=NSTextAlignmentCenter;
    patientNameLabel.minimumScaleFactor = 10.0f/12.0f;
    patientNameLabel.clipsToBounds = YES;
    patientNameLabel.backgroundColor = [UIColor clearColor];
    patientNameLabel.textColor = [UIColor blackColor];
    patientNameLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    NSString *subTitle =subTitleText;
    UIFont * customFont1 = [UIFont fontWithName:@"Helvetica Neue" size:14]; //custom font

    UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,25,320,20)];
    subTitleLabel.textAlignment = NSTextAlignmentCenter;

    subTitleLabel.text = subTitle;
    subTitleLabel.font = customFont1;
     subTitleLabel.textAlignment=NSTextAlignmentCenter;
    subTitleLabel.numberOfLines = 1;

    subTitleLabel.adjustsFontSizeToFitWidth = YES;
    subTitleLabel.minimumScaleFactor = 10.0f/12.0f;
    subTitleLabel.clipsToBounds = YES;
    subTitleLabel.backgroundColor = [UIColor clearColor];
    subTitleLabel.textColor = [UIColor blackColor];
    [titleView addSubview:patientNameLabel];
    [titleView addSubview:subTitleLabel];

Assigning image from another class

For some reason the image is not showing with this code:

YellowClass.h

@property (strong, nonatomic) IBOutlet UIImageView *myImage;

BlueClass.m

YellowClass *yellowClass = [[YellowClass alloc] init];
yellowClass.myImage.image = [UIImage imageNamed:@"Img.png"];

RKMappingResult has objects, but they NSLog as null

What I'm doing

Using RestKit, I'm making a GET request to get a JSON object that contains an array of User objects that populate a UITableView. I pass that array into a private NSArray called users which becomes _users (I'm still fuzzy on this). This works, and the table populates fine. I can access the individual objects in the _users array from my other methods, such as [UITableViewCell cellForRowAtIndex].

However, at the same time I pull the data down, and before I call [self.tableView reloadData] from inside the success block of [RKObjectManager getObjectsAtPath...], I want to process the individual objects a little bit.

My problem

Using [RKObjectManager getObjectsAtPath parameters success failure], success returns the RKMappingResult as expected, and I pass its array to a _users, which populates my UITableView. This works, but in the same success block, I try NSLog'ing _users[i] and it returns *nil description*. I know the values are being set at some point, because I populate my UITableViewCells by calling _users[i] in another method.

Hopefully more helpful info

When I NSLog(@"%@", _users) from inside the success block, and know for a fact there are 3 objects in the array, I see:

( (null), (null), (null) ).

I can provide more info, I'm just not sure what to put. I can also show my code, but it's basically out of the book from the RestKit docs.

How to create a global property(variable) in swift programming ? and pass value from other class

I have a class of UITableViewCell and that cell is intialized from another class that contains table view.I want to pass an integer value to cell class from tableview class.

In objective c it was simply done by making global variable and passing values when making instance of global variable class. I do not want any value at declaration time and this global variable will change the value and get the value when it is passing by another class.

I do not know where is mistake please see my code mentioned below-

UITableViewCell class :-

import UIKit

class PostHeaderCell: UITableViewCell {

var loopVariable: Int? // This is global variable that i have written

@IBOutlet weak var viewMain: UIView!
@IBOutlet weak var viewCategory: UIView!
@IBOutlet weak var mainViewHeight: NSLayoutConstraint!
@IBOutlet weak var topLayoutViewCategory: NSLayoutConstraint!
override func awakeFromNib() {
    super.awakeFromNib()
   print(loopVariable)

    viewMain.layer.cornerRadius=5.0
    viewMain.layer.borderColor = UIColor(red: 212.0/255.0, green: 217.0/255.0, blue: 221.0/255.0, alpha: 1.0).CGColor
    viewMain.layer.borderWidth=1.0
    var myVar = 50.0 as CGFloat
     for var i=0;i<loopVariable;i++
    {
        mainViewHeight.constant=mainViewHeight.constant+30
        var postCell :PostCategoryView?
        postCell = NSBundle.mainBundle().loadNibNamed("PostCategoryView", owner: self, options: nil)[0] as? PostCategoryView
        postCell!.frame=CGRectMake(10,myVar+10,postCell!.frame.size.width,50)
        print(postCell)
        myVar = myVar + 55.0;

    }
    self.layoutSubviews()
  }

    override func setSelected(selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
  }
}

Now, I implemented this UITableViewCell class in another class and passing loop variable value from that class, Please look below mentioned code for calling and instantiating PostHeaderCell- Class B:-

 var cell:PostHeaderCell! =     tableView.dequeueReusableCellWithIdentifier("PostHeaderCell",  forIndexPath: indexPath) as! PostHeaderCell
  cell.loopVariable=2
  return cell

Note -: I want to initialise the value of loop variable from Class B but it always give nil ( i have passed 2 as a value for loopVariable).

How to draw a sine line using SpriteKit?

This question is almost self-explanatory: I need to use SpriteKit to draw a line that looks like a sine wave, but I will also need to vary the amplitude of this wave later.

UITableViewCell is redrawing on dequeue

My setup

I have a UITableViewCell that is in my main storyboard in a UITableViewController. It gets populated with some JSON data pulled from a REST API that will cause each cell to be a variable height. There are UIImageViews, UILabels, all of different heights and styles, think Instagram-esque.

My problem

When I scroll to maybe the 5th or 6th cell, then go back up, they start redrawing and overlapping, so text gets mixed, lines get redrawn, etc.

What I've tried

This seems like a common problem on SO, so I've tried several posted solutions. It seems like my issue is probably the same problem as others face, which is, I am calling addSubview on my cell every time it dequeues, but I've tried checking to see if the cell already exists. I came across another post somewhere (sorry, I can't remember where), that suggests that because I am creating this in the storyboard, it is already initialized and if ( !cell ) will already return false, so I don't know how to prevent it from redrawing.

When I try removing the cell from the storyboard, and creating it programmatically, I get an error saying it can't find a cell with my identifier @"Cell".

I've also tried someone's solution of removing all subviews when I dequeue, so I used: for ( UIView *view in cell.contentView.subviews ) { if ([view isKindOfClass:[UIView class]]) { [view removeFromSuperview]; } }

and it doesn't find anything.

Changing an item in a custom UITableviewCell that is not visible

Suppose I have 10 items in my UITableView but only 4 items are being displayed at a time which changes when the user scrolls up or down. Now suppose I am on the 10th row so only the rows from 6->10 are being displayed. What should I do if I would like to change something on on the 2nd row.

Currently I have only 4 items and I am using the following approach

NSArray *cells = [tableView visibleCells];
for (CustomTableViewCell *cell in cells)
{
    if(cell.someproperty == 23)
    {
       //Show a certain image on the cell
       [cell.someButton setImage:[UIImage imageNamed:@"done.png"] forState:UIControlStateNormal];
    }
}

I realize the above approach probably wont work for items that are not being displayed (as those cells dont exist) because of dequeueReusableCellWithIdentifier being used. What options do I have any suggestions ?

iOS collectionView: how to scroll a cell to the top of the screen

I am wondering if there is a way to scroll a certain UICollectionViewCell to the top of the view? I tried the collectionView.scrollToItemAtIndexPath() method, but instead of scrolling the cell to the top of the view, it scroll the cell to the center of the view.

How to instantiate custom buttom from UIButton?

I need to make my button to CustomButton.

public class MyCustomButton : UIButton
{
    string customProperty;
}

I have already a UIButton. Now I need to make it MyCustomButton.
But explicit type cast results in crash.
How can I instantiate MyCustomButton from already existed UIButton?

I can't delete item from list Xcode

Hi I am trying out Xcode and I want to delete items from the list. I can get the delete button to show but once the delete button is clicked it wont delete. The delete code is at the end of the code. There is something missing in the deleting part of the code and I am not really sure what it is.

#import "ToDoListTableViewController.h"
#import "ToDoItem.h"
#import "AddToDoItemViewController.h"

@interface ToDoListTableViewController ()

@property NSMutableArray *toDoItems;

@end

@implementation ToDoListTableViewController

- (void)loadInitialData {
    ToDoItem *item1 = [[ToDoItem alloc] init];
    item1.itemName = @"Buy milk";
    [self.toDoItems addObject:item1];
    ToDoItem *item2 = [[ToDoItem alloc] init];
    item2.itemName = @"Buy eggs";
    [self.toDoItems addObject:item2];
    ToDoItem *item3 = [[ToDoItem alloc] init];
    item3.itemName = @"Read a book";
    [self.toDoItems addObject:item3];
}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue {
    AddToDoItemViewController *source = [segue sourceViewController];
    ToDoItem *item = source.toDoItem;
    if (item != nil) {
        [self.toDoItems addObject:item];
        [self.tableView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.toDoItems = [[NSMutableArray alloc] init];
    [self loadInitialData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:          
(NSInteger)section {
    // Return the number of rows in the section.
    return [self.toDoItems count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListPrototypeCell" forIndexPath:indexPath];
    // Configure the cell...
    ToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];
    cell.textLabel.text = toDoItem.itemName;

    if (toDoItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

Get exception at `CTFontManagerRegisterFontsForURL`

@implementation UIFont (FlatUI)

+ (void) initialize {
    [super initialize];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSArray *fontNames = @[@"Lato-Regular", @"Lato-Bold", @"Lato-Italic", @"Lato-Light"];
        for (NSString *fontName in fontNames) {
            NSURL * url = [[NSBundle mainBundle] URLForResource:fontName withExtension:@"ttf"];
            if (url) {
                CFErrorRef error;
                CTFontManagerRegisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeNone, &error);
            }
        }
    });
}

I add exception breakpoint, and every time it gets exception at CTFontManagerRegisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeNone, &error); How to solve it?enter image description here

ios How to know which UIView when I click from xib?

Because some reasons, I create a UIView xib file to reuse.
How to know which UIView when I click from xib?

I create a xib file extends UIView(named with XibView).
Then I drag two UIView(leftView,rightView) in the storyboard, and set the custom class "XibView" in XCode inspector window.

When I compile the code, It will get correct result that show two UIViews.

XibView.m file part code below:

 -(id) initWithCoder:(NSCoder *)aDecoder
 {
     self = [super initWithCoder:aDecoder];

     if( self )
     {

          UIView *containerView = [[[UINib nibWithNibName:@"XibView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
          CGRect newFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
          containerView.frame = newFrame;
          [self addSubview:containerView];
     }
    return self;
 }

 -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
      NSLog(@"tap in xib");
      ......
 }

But How can I know which UIView is my click?

// I add some detail description.

In the xib custom class, I will using post the notify to the uiviewcontroller and take some data when user click in xib(touchesBegan is in the xib custom class).

I have two uiview in the storyboard , these uiview will using the xib file.

so I want to know when I click which uiview, I can know which one user click.

What's the best way to implement below layout in iOS?

Now I have two ways to implement the layout:

First:

  • UIScrollView
    • UICollectionView
    • UICollectionView
    • ...

Second:

  • UICollectionView
    • UIScrollView
    • UIScrollView
    • ...

Are there any other better ways?

layout

Array won't print out results

I am attempting to put information into an array and print it out. I am making a game, but I'm not sure why it won't print. At most, the result is (null).

I am trying to put *firstItem into the denizen's inventory

 Denizen *firstDen = [[[Denizen alloc] initWithName:@"Mom," andHealth:4] autorelease];
    [bedroom spawn:firstDen];

 Item *firstItem = [[[Item alloc] initWithName:@"Stick" andWeight:8 andVolume:2 andDurability:1 andWorth:5] autorelease];
    [bedroom drop:firstItem];

 [firstDen addItemToInventory:firstItem];

then retrieve it using:

-(void)getWares
{
    NSArray *denInventoryItems = [wares allKeys];
    [self outputMessage: [NSString stringWithFormat:@"\nThese are the following items for sale: %@ \n.", [denInventoryItems componentsJoinedByString:@" "]]];
}

Here is my addItemToInventory where I suspect where the problem may lie, but I'm not sure. When I use a breakpoint it shows that firstItem is in wares, but nothing shows when I call getWares

-(void)addItemToInventory:(Item *)toAdd
{
    [wares addObject:toAdd];
}

Thank you very much for the help.

FBSDKShareDialog in iOS pre-specify certain page

In Facebook SDK v4 for iOS, I use FBSDKShareDialog to share contents to my Facebook page (which I'm one of the Page Admins).

- (IBAction)shareLink:(id)sender {
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentURL = [NSURL URLWithString:@"http://www.example.com"];
    [FBSDKShareDialog showFromViewController:self
                                  withContent:content
                                     delegate:nil];
}

It will launch Facebook App and a sharing dialog, which I'm allowed to change where I post the share contents.

Can I change the default sharing target to specific page? The default is "Your Timeline".

How do you manage (flag) a dirty state for a core data sqlite backed datasource

If you have an iOS app, using Core Data, and backed by Sqlite, how do you prefer to manage the dirty state of your data?

It looks like Core Data NSManagedObject has a 'hasChanges' method,

and as best I can tell, it looks like sqlite has nothing for managing dirty state.

At this point I'm leaning toward using variable(s) in my own classes to flag data as dirty, because I want to guarantee that if someone changes a field from 'Apple' to 'Orange' and then later comes back and changes it to 'Apple' again, that it absolutely NOT be flagged as dirty at that point, because it's returned to the original value it had when the app started. I'm guessing managing it myself is the way to go ?

Is this system object pointer code at all possible in Swift?

I was pointed to this objc snippet from WWDC 14, but I work on a Swift project.

CMIOObjectPropertyAddress   prop    = {
    kCMIOHardwarePropertyAllowScreenCaptureDevices,
    kCMIOObjectPropertyScopeGlobal,
    kCMIOObjectPropertyElementMaster
};
UInt32                      allow   = 1;

CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, NULL, sizeof(allow), &allow);

I then tried rewriting to Swift:

var prop : CMIOObjectPropertyAddress {
    kCMIOHardwarePropertyAllowScreenCaptureDevices
    kCMIOObjectPropertyScopeGlobal
    kCMIOObjectPropertyElementMaster
}

var allow:UInt32 = 1
CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, nil, sizeof(UInt32), &allow)

But it doesn't even validate. I don't know how to translate the CMIOObjectPropertyAddress struct. Xcode says

/Users/mortenjust/Dropbox/hack/learning/screenrec/screenrec/deleteme.swift:32:61: Cannot assign to a get-only property 'prop'

Attempting to Display Array on to UITableView

I am attempting to display an array which I receive from a JSON Dictionary onto a UITableView but I keep getting an error. I am trying to display all the comments for a given Instagram Picture onto a Table. Here is how I am attempting to display the cells:

  MessageTableViewCell *cell = (MessageTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:MessengerCellIdentifier];

  NSDictionary *instaPics = self.instagramData;
  NSArray *commentArray =  instaPics[@"comments"][@"data"];
  NSString *commentText = [commentArray valueForKey:@"text"]; // Error occurs here

  Message *message = self.messages[indexPath.row];

  cell.titleLabel.text = message.username;
  cell.bodyLabel.text = commentText;

Here is the error I receive:

 -[__NSArrayI length]: unrecognized selector sent to instance 0x7f913052db10
2015-05-05 22:16:08.848 Floadt[6061:514032] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x7f913052db10'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107d60c65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010763cbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000107d680ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x0000000107cbe13c ___forwarding___ + 988
    4   CoreFoundation                      0x0000000107cbdcd8 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x0000000106543ab4 -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 65
    6   UIKit                               0x000000010654390f -[UILabel textRectForBounds:limitedToNumberOfLines:] + 76
    7   UIKit                               0x00000001065473b9 -[UILabel _intrinsicSizeWithinSize:] + 170
    8   UIKit                               0x0000000106547499 -[UILabel intrinsicContentSize] + 76
    9   UIKit                               0x00000001069e5b6c -[UIView(UIConstraintBasedLayout) _generateContentSizeConstraints] + 33
    10  UIKit                               0x00000001069e5930 -[UIView(UIConstraintBasedLayout) _updateContentSizeConstraints] + 422
    11  UIKit                               0x00000001069ecd25 -[UIView(AdditionalLayoutSupport) updateConstraints] + 162
    12  UIKit                               0x0000000106547304 -[UILabel updateConstraints] + 274
    13  UIKit                               0x00000001069ec346 -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 242
    14  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    15  CoreFoundation                      0x0000000107c67354 CFArrayApplyFunction + 68
    16  UIKit                               0x00000001069ec2ed -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
    17  Foundation                          0x0000000105b021be -[NSISEngine withBehaviors:performModifications:] + 155
    18  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    19  CoreFoundation                      0x0000000107c67354 CFArrayApplyFunction + 68
    20  UIKit                               0x00000001069ec2ed -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
    21  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    22  UIKit                               0x00000001069eca0e __60-[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded]_block_invoke + 96
    23  UIKit                               0x00000001069ec6d6 -[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded] + 231
    24  UIKit                               0x00000001067d7531 -[UITableViewCellContentView updateConstraintsIfNeeded] + 94
    25  UIKit                               0x00000001069ecdde -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeeded] + 146
    26  UIKit                               0x00000001063e4a3d -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 114
    27  UIKit                               0x00000001063f0a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    28  QuartzCore                          0x00000001061b4ec2 -[CALayer layoutSublayers] + 146
    29  QuartzCore                          0x00000001061a96d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    30  UIKit                               0x00000001063e4675 -[UIView(Hierarchy) layoutBelowIfNeeded] + 607
    31  Floadt                              0x0000000104195848 -[SLKTextViewController viewWillAppear:] + 296
    32  UIKit                               0x00000001064a4fa1 -[UIViewController _setViewAppearState:isAnimating:] + 487
    33  UIKit                               0x00000001064c6395 -[UINavigationController _startCustomTransition:] + 887
    34  UIKit                               0x00000001064d23bf -[UINavigationController _startDeferredTransitionIfNeeded:] + 386
    35  UIKit                               0x00000001064d2f0e -[UINavigationController __viewWillLayoutSubviews] + 43
    36  UIKit                               0x000000010661d715 -[UILayoutContainerView layoutSubviews] + 202
    37  UIKit                               0x00000001063f0a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    38  QuartzCore                          0x00000001061b4ec2 -[CALayer layoutSublayers] + 146
    39  QuartzCore                          0x00000001061a96d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    40  QuartzCore                          0x00000001061a9546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    41  QuartzCore                          0x0000000106115886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    42  QuartzCore                          0x0000000106116a3a _ZN2CA11Transaction6commitEv + 462
    43  UIKit                               0x000000010636d626 _UIApplicationHandleEventQueue + 2140
    44  CoreFoundation                      0x0000000107c94431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    45  CoreFoundation                      0x0000000107c8a2fd __CFRunLoopDoSources0 + 269
    46  CoreFoundation                      0x0000000107c89934 __CFRunLoopRun + 868
    47  CoreFoundation                      0x0000000107c89366 CFRunLoopRunSpecific + 470
    48  GraphicsServices                    0x0000000109716a3e GSEventRunModal + 161
    49  UIKit                               0x0000000106370900 UIApplicationMain + 1282
    50  Floadt                              0x0000000104218c5f main + 111
    51  libdyld.dylib                       0x0000000109f2b145 start + 1
    52  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

Here is an example copy of the JSON:

{
    attribution = "<null>";
    caption =     {
        "created_time" = 1430877943;
        from =         {
            "full_name" = "Shreya M.";
            id = 25085898;
            "profile_picture" = "http://ift.tt/1KfELiO";
            username = "shreya_mandava";
        };
        id = 978597576956579585;
        text = "9+10????";
    };
    comments =     {
        count = 2;
        data =         (
                        {
                "created_time" = 1430878007;
                from =                 {
                    "full_name" = "Aleesha Toteja";
                    id = 17117902;
                    "profile_picture" = "http://ift.tt/1GZNFDM";
                    username = leeshtotes;
                };
                id = 978598112887967529;
                text = "DIRT \Ud83d\Ude3b";
            },
                        {
                "created_time" = 1430878307;
                from =                 {
                    "full_name" = "Shritha M.";
                    id = 375799796;
                    "profile_picture" = "http://ift.tt/1KfEHQl";
                    username = "shritha_m";
                };
                id = 978600630846098439;
                text = sigh;
            }
        );
    };
    "created_time" = 1430877943;
    filter = Normal;
    id = "978597574314167442_25085898";
    images =     {
        "low_resolution" =         {
            height = 306;
            url = "http://ift.tt/1GZNDvD";
            width = 306;
        };
        "standard_resolution" =         {
            height = 640;
            url = "http://ift.tt/1KfELiQ";
            width = 640;
        };
        thumbnail =         {
            height = 150;
            url = "http://ift.tt/1GZNFU0";
            width = 150;
        };
    };
    likes =     {
        count = 22;
        data =         (
                        {
                "full_name" = "Ronak Chopra";
                id = 347652824;
                "profile_picture" = "http://ift.tt/1KfELiU";
                username = "conak_rhopra";
            },
                        {
                "full_name" = "emily bach";
                id = 292615252;
                "profile_picture" = "http://ift.tt/1GZNDvF";
                username = "emily_bach_";
            },
                        {
                "full_name" = "\Ud83c\Udf38Trisha\Ud83c\Udf38";
                id = 303629882;
                "profile_picture" = "http://ift.tt/1KfELiW";
                username = trishddishh;
            },
                        {
                "full_name" = "Shritha M.";
                id = 375799796;
                "profile_picture" = "http://ift.tt/1KfEHQl";
                username = "shritha_m";
            }
        );
    };
    link = "http://ift.tt/1KfELiZ";
    location =     {
        id = 772010926;
        latitude = "38.913782928";
        longitude = "-77.383238738";
        name = "ft. dirt";
    };
    tags =     (
    );
    type = image;
    user =     {
        "full_name" = "Shreya M.";
        id = 25085898;
        "profile_picture" = "http://ift.tt/1KfELiO";
        username = "shreya_mandava";
    };
    "user_has_liked" = 0;
    "users_in_photo" =     (
                {
            position =             {
                x = "0.6703125";
                y = "0.246875";
            };
            user =             {
                "full_name" = "John Nguyen";
                id = 1477626916;
                "profile_picture" = "http://ift.tt/1GZNDLZ";
                username = bumbonguyen;
            };
        }
    );
}

Need to Print a Custom Header using obj-c

I am creating an NSView and it prints fine with this piece of code :

NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
[printInfo setHorizontalPagination:NSFitPagination];
[printInfo setHorizontallyCentered:YES];
[printInfo setVerticallyCentered:YES];
NSPrintOperation *operation = [NSPrintOperation printOperationWithView:printView printInfo:printInfo];

NSPrintPanel *printerPanel = operation.printPanel;

printerPanel.options = NSPrintPanelShowsPaperSize | NSPrintPanelShowsPageRange | NSPrintPanelShowsOrientation | NSPrintPanelShowsPageSetupAccessory | NSPrintPanelShowsPreview;

[operation runOperationModalForWindow:window delegate:nil
                       didRunSelector:nil contextInfo:nil];

I also have this code in applicationDidFinishLaunching

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:@YES forKey:NSPrintHeaderAndFooter];

Now if i try to override these methods

 - (void)drawPageBorderWithSize:(NSSize)pageSize
 - (NSAttributedString *)pageHeader

They are not even getting called. Anybody know why?

Why does my method call twice?

I have a method in my page view controller class thats meant to produce a set of numbers once, but instead it seems to fire twice for some reason? Can anyone tell me why its firing twice?

This is what the console fires http://ift.tt/1GZJrMk What is happening, why isnt it working like it should?

I want my page view controllers to loop as the user scrolls forward, while I have five different numbers that constantly go up at the same time but don't loop, they just infinitely increase.

Swipe Backwards method

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
     viewControllerBeforeViewController:(UIViewController *)viewController
{
   NSUInteger currentIndex = [myViewControllers indexOfObject:viewController];


    swipeTotal = swipeTotal - 1;



    if (swipeTotal > 4) {
        firstFive = true;
        //   NSLog(@"First Five Passed");
    }else{
        firstFive = false;
        //  NSLog(@"First Five False");
    }

    // NSLog(@"Swipe Total is %d",swipeTotal);

    if (currentIndex == 0) {
        swipeContent1 = swipeTotal;
        swipeContent2 = swipeTotal + 1;
        swipeContent3 = swipeTotal + 2;
        swipeContent4 = swipeTotal - 2;
        swipeContent5 = swipeTotal - 1;
    }
    if (currentIndex == 1) {
        swipeContent1 = swipeTotal - 1;
        swipeContent2 = swipeTotal;
        swipeContent3 = swipeTotal + 1;
        swipeContent4 = swipeTotal + 2;
        swipeContent5 = swipeTotal - 2;
    }
    if (currentIndex == 2) {
        swipeContent1 = swipeTotal - 2;
        swipeContent2 = swipeTotal - 1;
        swipeContent3 = swipeTotal;
        swipeContent4 = swipeTotal + 1;
        swipeContent5 = swipeTotal + 2;
    }
    if (currentIndex == 3) {
        swipeContent1 = swipeTotal + 2;
        swipeContent2 = swipeTotal - 2;
        swipeContent3 = swipeTotal - 1;
        swipeContent4 = swipeTotal;
        swipeContent5 = swipeTotal + 1;
    }
    if (currentIndex == 4) {
        swipeContent1 = swipeTotal + 1;
        swipeContent2 = swipeTotal + 2;
        swipeContent3 = swipeTotal - 2;
        swipeContent4 = swipeTotal - 1;
        swipeContent5 = swipeTotal;
    }

    if (firstFive == true) {


    if (currentIndex == 0) {
        currentIndex = 4;

    }else{
        --currentIndex;
        currentIndex = currentIndex % (myViewControllers.count);
    }

    }else{
        if (currentIndex > 0)
        {
            return [myViewControllers objectAtIndex:currentIndex-1];
            // return the previous viewcontroller
        } else
        {
            return nil;
            // do nothing
        }

    }


     /*
        content1 = [users objectAtIndex:swipeContent1];
        content2 = [users objectAtIndex:swipeContent2];
        content3 = [users objectAtIndex:swipeContent3];
        content4 = [users objectAtIndex:swipeContent4];
        content5 = [users objectAtIndex:swipeContent5]; */

    NSLog(@"Content 1 = %d",swipeContent1);
    NSLog(@"Content 2 = %d",swipeContent2);
    NSLog(@"Content 3 = %d",swipeContent3);
    NSLog(@"Content 4 = %d",swipeContent4);
    NSLog(@"Content 5 = %d",swipeContent5);




    return [myViewControllers objectAtIndex:currentIndex];
}

Swipe forwards method

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [myViewControllers indexOfObject:viewController];


    if (swipeTotal > 4) {
        firstFive = true;

        //      NSLog(@"First Five Passed");
    }else{
        firstFive = false;
        //     NSLog(@"First Five False");
    }

    //  NSLog(@"Swipe Total is %d",swipeTotal);

    ++currentIndex;
    currentIndex = currentIndex % (myViewControllers.count);

    swipeTotal = swipeTotal + 1;

    if (currentIndex == 0) {
        swipeContent1 = swipeTotal;
        swipeContent2 = swipeTotal + 1;
        swipeContent3 = swipeTotal + 2;
        swipeContent4 = swipeTotal - 2;
        swipeContent5 = swipeTotal - 1;
    } else if (currentIndex == 1) {
        swipeContent1 = swipeTotal - 1;
        swipeContent2 = swipeTotal;
        swipeContent3 = swipeTotal + 1;
        swipeContent4 = swipeTotal + 2;
        swipeContent5 = swipeTotal - 2;
    } else if (currentIndex == 2) {
        swipeContent1 = swipeTotal - 2;
        swipeContent2 = swipeTotal - 1;
        swipeContent3 = swipeTotal;
        swipeContent4 = swipeTotal + 1;
        swipeContent5 = swipeTotal + 2;
    } else if (currentIndex == 3) {
        swipeContent1 = swipeTotal + 2;
        swipeContent2 = swipeTotal - 2;
        swipeContent3 = swipeTotal - 1;
        swipeContent4 = swipeTotal;
        swipeContent5 = swipeTotal + 1;
    } else if (currentIndex == 4) {
        swipeContent1 = swipeTotal + 1;
        swipeContent2 = swipeTotal + 2;
        swipeContent3 = swipeTotal - 2;
        swipeContent4 = swipeTotal - 1;
        swipeContent5 = swipeTotal;
    }

    NSLog(@"Content 1 = %d",swipeContent1);
    NSLog(@"Content 2 = %d",swipeContent2);
    NSLog(@"Content 3 = %d",swipeContent3);
    NSLog(@"Content 4 = %d",swipeContent4);
    NSLog(@"Content 5 = %d",swipeContent5);


    return [myViewControllers objectAtIndex:currentIndex];
}

How to get the url domain name with objective-c

When i get a url likehttp://ift.tt/1GZJuYo,I just need the abc.com,what should I do?

Node Deletion in Objective-C Binary Search Tree - Pointers?

I see a lot of examples of node deletion with C/C++ for binary search trees. I'm trying to write this in objective C and I'm unsure if I want to use a single or double pointer approach or neither? Any links or advice would be great. Here's my code to create/insert node to the tree if that is helpful

-(Node*) Insert:(Node*)root withData:(int) data {
    //Empty root
    if(root == NULL) {
        root = [self GetNewNode:data];
    }
    // If data is less insert in left tree
    else if(data <= root.data) {
        root.left = [self Insert:root.left withData:data];
    }
    // If data is more insert in right tree
    else {
        root.right = [self Insert:root.right withData:data];
    }
    return root;
}

and

Node* root = NULL;  // Creating an empty node on the tree
Tree* tree = [[Tree alloc]init];

 // Setup the tree
root = [tree Insert:root withData:15];
root = [tree Insert:root withData:20];
root = [tree Insert:root withData:25];

IOS Bar button is incorrect size

I have UIBarButton image that isn't working. It shows up in the right spot but the image is super duper zoomed in. why? The sizes of the image for 1x 2x and 3x are 22x22, 44x44, 66x66 respectively.

UIBarButtonItem *addFriendBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add friend button"]
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:self
                                                                      action:@selector(transitionToAddFriends)];
self.navigationItem.rightBarButtonItem = addFriendBarButton;

How can I fetch only object rows sent&mapped back from server when using RestKit+CoreData?

I am using RestKit 0.2.x with Core Data and following the standard tutorials, ie:

  • Create Core Data model and use mogenerator to make code
  • Instantiate object manager with base URL
  • Create managed object context and persistent store
  • Create entity mappings for all entities returned by my web service
  • Create response descriptors for all web service endpoints and entities
  • Add response descriptor to object manager

Everything seems to be "working" just fine ... I can call

[[RKObjectManager sharedManager] getObjectsAtPath:_requestPath parameters:_requestParameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

... all day long, and I then I keep handling with (as shown in the tutorials)

- (void)requestSuccess {
    NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:_entityName];
    fetchRequest.sortDescriptors = @[_defaultSortDescriptor];

    NSError *error = nil;
    requestData = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    [_delegate handleRequestSuccess:self withData:requestData];
    //[self cleanupRequestBeforeSuccessWithData:requestData];
    [self completeRequest];
}

Now the problem is that at least by default, RestKit+CoreData actually persists your GET'ted objects to its own persistence store, or something like that. I'll explain the "cleanupRequest..." in a moment.

That kind of defeats the purpose of trying to allow the users to specify parameters at the level of the web service client, because all of the objects seem to end up in the same place anyway.

For instance, let's say I have a method /api/endpoint?queryString and I call it with two different sets of parameters:

[[RKObjectManager sharedManager] getObjectsAtPath:@"/api/endpoint" parameters:PARAMS_ONE success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

[[RKObjectManager sharedManager] getObjectsAtPath:@"/api/endpoint" parameters:PARAMS_TWO success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

If I then blindly follow the tutorials about how to retrieve my objects, my callbacks are then identical!

NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EndpointDataTransferObject"];
fetchRequest.sortDescriptors = @["endpointDataTransferObjectID"];

NSError *error = nil;
requestData = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

The result, of course, is that the my delegate gets sent (pseudocode) requestData WHERE PARAMS_ONE on the first call, and then requestData WHERE PARAMS_ONE UNION requestData WHERE PARAMS_TWO on the second call.

Now all I really want is to be able to conduct the NSFetchRequest on only those items mapped from the web service. I think this is a totally reasonable expectation, so clearly I am missing something because whoever wrote this library is much more clever than I.

For instance, if I could somehow get an NSArray of all the objects from the two parameters it provides in the success block (RKRequestRequestOperation *o, RKMappingResult *m) - and if I can, please tell me how!!! - then my problem would be solved, and I could enjoy the caching without having to worry about whether my filters are being ignored.

What I do not want to do, however, is this:

  • Call getObjectsAtPath: parameters: success: failure: with parameters and/or path representing a sort of "server-side" predicate
  • On success, create a NSFetchRequest and a client-side predicate that mirrors my server-side predicate

This approach seems really really dumb, and yet, I don't know any better. But I refuse to do that. It is error-prone, redundant, and potentially resource-intensive.

So instead, I've opted to add a little method cleanupRequestBeforeSuccessWithData at the end of my success callback before calling completion:

- (void)cleanupRequestBeforeSuccessWithData:(NSArray *)managedObjects {
    NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;

    for (NSManagedObject *o in managedObjects) {
        [managedObjectContext deleteObject:o];
    }

    NSError *error = nil;
    [managedObjectContext save:&error];
}

This is ugly but it sure gets the job done. Now it totally empties the cache, but I'd rather have to make requests over and over again than to form "server-side" predicates with URL's and then form client-side NSPredicates.

What am I missing about how this is supposed to work? Clearly, I'm missing something big.

How to save fields correctly with NSUserDefaults?

I'm creating a program that saves a String from one text field and an integer from a second text field. I am trying to use NSUserDefaults, but I can't seem to get either of them to save correctly when I run the program. It crashes when I press the save button with the breakpoint while handling the NSUserDefaults. Am I doing something wrong? I skimmed through the documentation, but it didn't help. Can I even use 2 different instances of NSUserDefaults?

- (IBAction)save:(id)sender {
//Save stuff fropm textfields
NSString* name = _nameText.text;
NSInteger count = [[_countText.text] intValue];

//Save string
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:name forKey:@"name"];
[defaults synchronize];

//Save int
NSUserDefaults* defaults2 = [NSUserDefaults standardUserDefaults];
[defaults2 setInteger:count forKey:@"count"];
[defaults2 synchronize]; }


- (IBAction)load:(id)sender {
//Load stuff from NSUserDefaults
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* loadstring = [defaults objectForKey:@"name"];
_nameText.text =  loadstring;

NSUserDefaults* defaults2 = [NSUserDefaults standardUserDefaults];
NSInteger loadint = [defaults2 integerForKey:@"count"];
_countText.text = [NSString stringWithFormat:@"%li", (long)loadint];}

Get UITextView Gesture (To Identify Location of Tap/LongPress)

I'm rather confident [editable] UITextView's become firstResponder when a long press or tap gesture occurs within the scrollView. I want to identify where in the view this touch occured. Digging through the documentation and source code didn't yield me much. I might be going about this wrong. My concern is a race condition if I just add my own tap recognizer (how can I be sure it is called before the textView's delegate methods).

For practical clarification, I want to call two similar functions from a delegate function (editingDidBegin) but depending if they touched the left or right half of the text view, I want to call either of the two.

Add different images to UIImageView of cells in UITableView

Needless to say, i am a novice. I am trying to add images and text to a UITableView. I have been able to add the text but I am having problems with adding different images to the desired text.

I have 2 separate PHP codes for 1 database:

  • The first gets the text and an id for the image assigned to the text (imageID)
  • The second uses the id (from the first PHP) to acquire the image

My code is fine but currently only 1 image is appearing for all the text

My question is how do I assign each image to their text ?

And how do I not assign an image to the text that do not have images as some of the texts don't have images with them?

My code is as follows:

Connection and data download:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations
        NSMutableArray *list = [[NSMutableArray alloc] init];

    // Parse the JSON that came in
    NSError *error;
    jsonArray = [NSJSONSerialization JSONObjectWithData:downloadedData options:NSJSONReadingAllowFragments error:&error];

    // Loop through Json objects, create question objects and add them to our questions array
    for (int i = 0; i < jsonArray.count; i++)
    {
        jsonElement = jsonArray[i];

        // Create a new cell object and set its props to JsonElement properties
        if (![jsonElement [@"Thought"] isEqual:[NSNull null]])
        {
            NSString *listText =jsonElement [@"Thought"];
            if ([listText length] > 0)
            {
                NSString *cellText = jsonElement[@"Thought"];
                [list addObject:cellText];
                NSLog(@"list Cell: %@", cellText);
            }

            if (![jsonElement [@"filename"] isEqual:[NSNull null]])
            {
                imageID = jsonElement[@"id"];
            }
            NSLog(@"Cell Image: %@", imageID);
        }
    }
    [[self tableView1] reloadData];
}

Cells in the table:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleIdentifier = @"SimpleIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
    }

    cell.textLabel.text = [list objectAtIndex:indexPath.row];
    cell.textLabel.font = [UIFont italicSystemFontOfSize:20];

    if ([imageID length] > 0)
    {
        urlStr = [NSString stringWithFormat:@"http://ift.tt/1QgEkJ2", imageID];
        NSURL *imageUrl = [NSURL URLWithString:urlStr];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
        cell.imageView.image = imageLoad;
    }

    return cell;
}

CGRectMake 4 Lines with horizontal displacement for each line?

I have a method:

-(void) generateButtons {
int positionsLeftInRow = BUTTONS_PER_ROW;
int j = 0;

for (int i = 0; i < [self.Model.buttons count]; i++) {
    NSInteger value = ((Model *)self.Model.buttons[i]).value;

    ButtonView *cv = [[ButtonView alloc] initWithFrame:CGRectMake((i % BUTTONS_PER_ROW) * 121 + (i % BUTTONS_PER_ROW) * 40 + 205, j * 122 + j * 40 + 320, 125, 125) andPosition:i andValue:value];

    if (!((Model *)self.Model.buttons[i]).outOfPlay) {
        [self.boardView addSubview:cv];


        if ([self.Model.usedButtons containsObject: self.Model.buttons[i]]) {

            [self.usedButtons addObject: cv];

            [cv flip];

        }
    }

    if (--positionsLeftInRow == 0) {
        j++;
        positionsLeftInRow = BUTTONS_PER_ROW;
    }
}

}

So, my question is, how to make a horizontal displacement for each line, that the second line is displaced from 1st and 3rd for example.

UIPageControl problems, Objective-C

I have been working on implementing UIPageViewController for some time now. I have went through many problems that i managed to solve by myself and with some extra help. Now i am stuck with the last part and that is the UIPageControl.

I got two problems that i would like some help with:

Problem 1: Is there any simple way to resize the dots for the pageControl?

Problem 2: This is how it is built:

enter image description here

I know it is hard to see but i will explain them starting from the upper left corner and going to right. First VC is simply a Navigation Controller pointing to a UITableViewController.

in the second row the first VC is the datasource delegate for the UIPageVIewController. The one next to it is the PageViewController, The two UITableView's next to it is the "pages" that are in the UIPageViewController. And the last one is the PageContentViewController.

So i added this code in viewDidLoad to the datasource VC meaning the first VC in the second row:

self.navigationController.delegate = self;
CGSize navBarSize = self.navigationController.navigationBar.bounds.size;
CGPoint origin = CGPointMake( navBarSize.width/2, navBarSize.height/2 );
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(origin.x, origin.y+16,
                                                                   0, 0)]; //Here added 45 to Y and it did the trick



self.pageControl.pageIndicatorTintColor = navbarColor;
self.pageControl.currentPageIndicatorTintColor = [UIColor lightGrayColor];

[self.pageControl setNumberOfPages:2];

and

- (void)navigationController:(UINavigationController *)navigationController     willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    int index = [self.navigationController.viewControllers indexOfObject:viewController];
    self.pageControl.currentPage = index;  }

Which gives me this result:

enter image description here

Which is perfect, I can swipe right and left and the PageControl shows the right indicator etc. However when i leave the "UIPageViewController" meaning when i click back. The PageController still appears in the first VC in the first picture. Why does it tag along and not get removed and how can i solve this?

If you need extra codes / pictures that would make it easier to understand just tell me. Thank you!

Content of the UIViewController doesn't show up even though the UINavigation bar is there

So I'm trying to switch from one UIViewController to another using the navigation controller. I know for sure that the new controller goes successfully through the custom init method and creates two UIBarButtons. However, the content of the screen (4 labels, 3 textfields, 1 UIImageView) doesn't show up. Instead, I just see a grey screen.

Passing the NSLog message through the ViewDidLoad,ViewWillLoad and ViewWillAppear showed that all these were successfully executed.

Here is the gitHub repo if you want to take a look: http://ift.tt/1cjGCZv

Here is the code that I use to pass a new controller:

// Create a new student and add it to the store
  Student* newStudent = [[StudentStore sharedStore] createStudent];

StudentDetailViewController *detailViewController = [[StudentDetailViewController alloc] initForNewStudent:YES];

detailViewController.student = newStudent;

detailViewController.dismissBlock = ^{
    [self.tableView reloadData];
};

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

navController.modalPresentationStyle = UIModalPresentationFormSheet;

[self presentViewController:navController animated:YES completion:NULL];

Animation is not working as expeced

I implemented corePlot in xcode and I'm using the pie chart. I'm trying to create a 3d flip animation while the chart reloads. Here is the code:

CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
scaleAnimation.toValue = [NSNumber numberWithFloat:0.5];
scaleAnimation.duration = 1.0f;
scaleAnimation.removedOnCompletion = NO;
[self.pieChart addAnimation:scaleAnimation forKey:@"scale"];

[self.pieChart reloadData];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
animation.fromValue = [NSNumber numberWithFloat:0.5];
animation.toValue = [NSNumber numberWithFloat:1.0];
animation.duration = 1.0f;
[self.pieChart addAnimation:animation forKey:@"scale"];

I didn't get desirable effects. I think what's happening is, both animations are happening at once. (Though I'm not sure that is what's happening.)

Also, is it possible to add z-depth? If so, how?

platform.hpp file not founde [iOS]

I try import parse with cocoapods in my project but have error like platform.hpp file not founde, how fix it? iOS trouble with libzmq

SceneKit animate node along path

I have a box node

_boxNode = [SCNNode node];
_boxNode.geometry = [SCNBox boxWithWidth:1 height:1 length:1 chamferRadius:0];
_boxNode.position = SCNVector3Make(0, 0, -2);
[scene.rootNode addChildNode:_boxNode];

I have a path

CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(-2, -2, 4, 4), nil);

I want to have my box travel along my path.

How do I do this in SceneKit?

UIImageView in UICollectionVIew does not display image until "cell" is clicked on

In my collectionView, each cell has an image. The image is pulled from the web with a URL obtained from mySQL database. The entire code of my UICollectionView is here, and the cells are custom made:

#import "DealsCollectionView.h"
#import "DealsCell.h"
#import "DealsModel.h"
#import "Deal.h"

@interface DealsCollectionView ()
{
DealsModel *_homeModel;
}

@property UIActivityIndicatorView *spinner;
@property NSMutableArray *deals;
@property NSCache *imageCache;

@end

@implementation DealsCollectionView

-(void)itemsDownloaded:(NSArray *)items
{
// This delegate method will get called when the items are finished downloading

// Set the downloaded items to the array
_deals = [items copy];

[_spinner stopAnimating];

// Reload the table view
[self.collectionView reloadData];
}


- (instancetype) initWithCollectionViewLayout:(UICollectionViewLayout *)layout
{
self = [super initWithCollectionViewLayout:layout];

if (self) {
    // alloc and init the various (Mutable)Array properties
    self.deals = [[NSMutableArray alloc] init];
    self.imageCache = [[NSCache alloc] init];

    // Set Title
    self.navigationItem.title = @"Deals from Our Sponsors";



    // Create new HomeModel object and assign it to _homeModel variable
    _homeModel = [[DealsModel alloc] init];

    // Set this view controller object as the delegate for the home model object
    _homeModel.delegate = self;

    // Call the download items method of the home model object
    [_homeModel downloadItems];

}

return self;
}


- (void)viewDidLoad {
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = NO;

// Create a spinner
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

spinner.center = CGPointMake(screenWidth/2.0, screenHeight/5.0);
spinner.hidesWhenStopped = YES;
[self.view addSubview:spinner];
[spinner startAnimating];
_spinner = spinner;



// Do any additional setup after loading the view.

UINib *cellNib = [UINib nibWithNibName:@"DealsCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"dealCell"];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _deals.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DealsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dealCell" forIndexPath:indexPath];

// Configure the cell
Deal *thisDeal = [_deals objectAtIndex:indexPath.row];

UILabel *nameLabel = (UILabel *) [cell viewWithTag:1];
nameLabel.text = thisDeal.name;

UILabel *offerLabel = (UILabel *) [cell viewWithTag:2];
offerLabel.text = thisDeal.offer;

UILabel *descriptionLabel = (UILabel *) [cell viewWithTag:3];
descriptionLabel.text = thisDeal.businessDescription;

UILabel *addressLabel = (UILabel *) [cell viewWithTag:4];
addressLabel.text = thisDeal.address;



// Configure the image
UIImageView *imageView = (UIImageView *) [cell viewWithTag:6];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.clipsToBounds = YES;

UIImage *dealLargeImage = [self.imageCache objectForKey:thisDeal.largeImage];
imageView.image = dealLargeImage;
if (dealLargeImage == nil) {

    NSURLSessionConfiguration *sessionConfig =
    [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate: self delegateQueue:nil];
    NSURLSessionDataTask *imageData = [session dataTaskWithURL:[NSURL URLWithString: thisDeal.largeImage]
                                             completionHandler:^(NSData *data,
                                                                 NSURLResponse *response,
                                                                 NSError *error) {
                                                 // handle NSData
                                                 UIImage *image = [UIImage imageWithData:data];
                                                 //thisDeal.image = image;
                                                 [self.imageCache setObject:image forKey:thisDeal.largeImage];
                                                 imageView.image = image;

                                                 dispatch_async(dispatch_get_main_queue(), ^{
                                                     [self.collectionView reloadData];
                                                 });
                                             }];
    [imageData resume];
}

return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(20, 10, 20, 10); // top, left, bottom, right
}

The code for my custom UICollectionView cells are pretty much entirely blank, except for the XIB. The cell will appear, with all the labels set appropriately, etc. However, the image of the imageView is shown as black (the background color), until I click on it, in which case that cell's imageView (and only that cell's imageView) has its image appear. I'm wondering how I can get these images to appear as the view loads, rather than having to click on them.

NSTimer starts, stops, and continues after window closes

So here is what's happening in human logic (but not suppose to be).

  1. My View controller loads
  2. retrieves my images from Parse successfully
  3. sets the first retrieved image equal to my UIImageView image
  4. starts my timer of 5 Seconds (I think)
  5. And then it doesn't do anything, just remains on the very first image
  6. Once I close the window (which was presented modally by previous view controller), I see in the console my println() outputs and my timer begins to work.

The GOAL: To present an image in my UIImageView for 5 seconds or so, and then display the next one in line (imageArray).

Is it my timer that's causing this pause in function, or does it have something to do with how my code is arranged? All suggestions/help are very much appreciated as this is a very frustrating issue.

This is in Swift language, but I can read Objective-C.

Here is my code for the class:

//
//  ImageDisplayViewController.swift
//  
//
//  Created by on 5/3/15.
//
//

import Cocoa
import ParseOSX

class ImageDisplayViewController: NSViewController {


@IBOutlet weak var imageView: NSImageView!

var venue: String!
var imageArray = [(Int, NSImage)]()
var image: NSImage!
var timeToDisplay: Int = 0

var timer = NSTimer()

override func viewDidLoad() {
    super.viewDidLoad()

    venue = "Bees"
    loadImages()


}

var k: Int = 0

func presentNextImage() {
    if(k<imageArray.count) {
    imageView.image = imageArray[k].1
    timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("presentNextImage"), userInfo: nil, repeats: false)
        println(timer.timeInterval)
        //imageView.image = imageArray[k].1
        println("k is \(k)")
        k++
        println("Just set a new imageView.image")
    } else {
        println("K is n longer <imageArray.count")
    }
}



func loadImages() {
    var query = PFQuery(className:groupz)
    query.whereKeyExists("imageFile")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {
            println("Successfully retrieved \(objects!.count) objects.")
            // Do something with the found objects
            if let objects = objects as? [PFObject] {
                for object in objects {
                    let thumbNail = object["imageFile"] as! PFFile
                    self.image = NSImage(data: thumbNail.getData()!)
                    let time: AnyObject? = object["displayTime"]
                    self.timeToDisplay = time!.integerValue

                    let tempTuple = (self.timeToDisplay, self.image!)
                    self.imageArray.append(tempTuple)

                }
            }
            println("imageArray.count is: \(self.imageArray.count)")
            self.presentNextImage()
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
    }
}

}