vendredi 8 mai 2015

Xcode lldb not storing properties

I am currently using Xcode 6.3.1. In the debug area, I pause the app and store a property like p NSString * $test = @"word" in the debug window. If I type po $test the output would be word, this is perfect but as soon as I let the app run. When I pause it again out of scope of the class/method it seems that they property is nil. When I type p $test my output would be (NSString *) $test =.

Is this a bug with this version of Xcode or can it be fixed?

Thanks

How to check the validation of edit text for pan card in objective c?

I have to validate the test is a valid pan card with help of some regular expression.can any one help this out.

I found a good solution in java and check out the below stack
How to check the validation of edit text for pan card?

View factory for iOS

I am trying to create a View factory for iOS and I am getting into some trouble. The view factory should be a able to create multiple UIImageViews, MKMapViews or UIWebViews and add them to a view vertically. I have a problem with the web view cause I have to wait for webViewDidFinishLoad. If the methods are implemented in the ViewController which implements the UIWebViewDelegate and the delegate of the webviews is set to the controller everything works fine. The thing is that I want to put all of this in a separate class but the webViewDidFinishLoad is never been called. Is there a way to achieve that? Tell me if you need any code

Code: Part is added

- (void)addPart
{
  if (self.viewPartStrings.count != 0) {
    NSString *viewPartString = [self.viewPartStrings objectAtIndex:0];
    NSString *viewPartIdentifier = [self getViewPartIdentifier:viewPartString];
    NSString *viewPartDefinition = [self getViewPartDefinition:viewPartString];
    if ([viewPartIdentifier isEqualToString:kWeb]) {
        [self createTextWebViewPart:viewPartIdentifier];
    } else if ([viewPartIdentifier isEqualToString:kMap]) {
        [self createMapViewPart:viewPartDefinition];
    } else if ([viewPartIdentifier isEqualToString:kImage]) {
        [self createImageViewPart:viewPartDefinition];
    }
  }
}

Views are created:

- (void)createTextWebViewPart:(NSString *)viewPartText
{
    WebViewPart *webViewPart = [[WebViewPart alloc]initWithFrame:[self getViewPartFrameForHeight:0]];
    [webViewPart createViewForText:viewPartText];
    [webViewPart setDelegate:self];
}

- (void)createImageViewPart:(NSString *)viewPartDefinition
{
    //create image
}

- (void)createMapViewPart:(NSString *)viewPartDefinition
{
    //create map
}

But here is the point. This method is never called. Not if the class extends NSObject and not if the class extends UIView:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGRect frame = webView.frame;
    frame.size.height = 1;
    webView.frame = frame;
    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
    int height = frame.size.height + 70;
    [self addToView:webView forHeight:height];

}

Kahn algorithm & reachability

For learning purpose I'm developping an application that in real life would work basically like Quartz Composer or the recent Vuo. I'm building the graph of nodes on a Core Data Framework basis.

Basically I have a Node entity with a to-many relationship with Input and Output entities (a node can have multiple inputs and multiple outputs). Input has a to-one relationship to a Connection entity, while Output has a to-many relationship with the latter (an input can have only one connection, while an output can have many).

To read the graph I'm using a Topological Sorting algorithm (Kahn's one), described here. The code is as follows :

/**
 * Get all nodes.
 */
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Node"];
NSMutableArray *nodes = [[[_document managedObjectContext] executeFetchRequest:request error:nil] mutableCopy];
/**
 * Reset the nodes 'visited' flag.
 */
[self reset:nodes];
/**
 * Get sources: predicate for nodes without input ports or with input ports without connections.
 */
[request setPredicate:[NSPredicate predicateWithFormat:@"inputs == nil OR ALL inputs.connection == nil"]];
NSMutableArray *sources = [[[_document managedObjectContext] executeFetchRequest:request error:nil] mutableCopy];
/**
 * Perform a topological sort.
 */
while ([sources count] > 0) {
    /**
     * While there are sources.
     */
    NSManagedObject *node = [sources lastObject];
    /**
     * Add the node to the tail of the final graph (NSMutableArray).
     */
    [_graph addObject:node];
    [sources removeLastObject];
    /**
     * Outputs.
     */
    NSMutableSet *outputs = [node valueForKey:@"outputs"];
    for (NSManagedObject *output in outputs) {
        /**
         * Get output connections.
         */
        NSMutableSet *connections = [output valueForKey:@"connections"];
        for (NSManagedObject *connection in connections) {
            /**
             * Set the connection as already visited.
             */
            [connection setValue:@(YES) forKey:@"kConnectionVisited"];
            NSManagedObject *n = [[connection valueForKey:@"destination"] valueForKey:@"node"];
            /**
             * Set the 'source' flag to YES by default.
             */
            BOOL isNewSource = YES;
            /**
             * Get connected inputs.
             */
            NSMutableSet *inputs = [n valueForKey:@"inputs"];
            for (NSManagedObject *input in inputs) {
                /**
                 * Check if one of the input connections was visited.
                 * If not, then we need to process this connection and
                 * don't add it to sources for next pass.
                 */
                if ([[[input valueForKey:@"connection"] valueForKey:@"kConnectionVisited"] isEqualTo:@(NO)]) {
                    isNewSource = NO;
                    break;
                }
            }

            if (isNewSource) {
                [sources addObject:n];
            }
        }
    }
}
/**
 * Set the execution index for display.
 */
for (int i; i < [_graph count]; i++) {
    [[_graph objectAtIndex:i] setValue:@(i) forKey:@"kNodeExecutionIndex"];
}

I'm trying to understand the logic of how (and where in this code) I'd have to compute reachability for each Node (therefore for each Input) entity, if it is possible.

My questions are :

  • Is it possible to compute the reachability of nodes inside the Kahn's algorithm ?
  • If appropriate, where and how to do it, so I can understand why it is working ?

Thank you.

XCode compile variables

I am developing a chat application. I am using Quickblox as backend as service. I have created 3 projects (each one different mode) on the admin panel : development, staging and production. Each mode has its specific properties. I want each mode to be activated as follows :

  • Development : debug.
  • Staging : client release.
  • Production : app store deployment.

How can i achieve that automatically (via XCode) without having to change my global variables values depending on the mode ?

How Access instance Variable in Class method

I am a new iOS developer, i try to access instance variable in class method but i can't access.please give me some solution here is my code

h.file

@protocol ServiceProvideDelegate <NSObject>
@required
-(void)responeFromURL:(NSDictionary*)dicResponse;
@end

@interface AFNetworkServiceProvider : NSObject
{
   id <ServiceProvideDelegate> delegate;
}
@property (nonatomic,strong) id delegate;

+(NSDictionary*)getResponseFromURL:(NSURL*)url;
@end

m.file

@implementation AFNetworkServiceProvider
@synthesize delegate;
+(void)getResponseFromURL:(NSURL *)url
{
 @try
 {
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *requestOperation=[[AFHTTPRequestOperation alloc]initWithRequest:request];
    requestOperation.responseSerializer=[AFJSONResponseSerializer serializer];

    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        if(delegate)
        {
          [delegate responeFromURL:responseObject]
       } 
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Response Error :- %@",[error localizedDescription] );
    }];
    [requestOperation start];    
}
@catch (NSException *exception)
{

}
@finally {

}
}

Try to Returne Response object using protocol method, but i get the error at if(delegate) unable to access instance variable in class method

How to customize iOS UINavigationItem?

I suppose that this is duplicate, but after a research I can not understand how to customise UINavigationItem.

I have custom ViewController (VC) which implements custom class SWRevealViewController (I need to create sliding menu). I have Menu VC and for each element of the menu I have Navigation VC with custom VC for each element of the menu.

To work each back button must be defined in Designer and to have outlet (I also added outlet for navigation item):

@property (weak, nonatomic) IBOutlet UIBarButtonItem *btnSidebareMenu;
@property (weak, nonatomic) IBOutlet UINavigationItem *niTitle;

In my .m file I have this code:

self.navigationItem.title = @"Custom title";

self.navigationController.topViewController.navigationItem.leftBarButtonItem = self.btnSidebareMenu;
self.btnSidebareMenu.enabled=TRUE;
self.btnSidebareMenu.style=UIBarButtonSystemItemRefresh;

to customise button and title for each Menu element VC.

I use this code to manage navigation to menu:

// Manage menu button
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
    [self.btnSidebareMenu setTarget: self.revealViewController];
    [self.btnSidebareMenu setAction: @selector( revealToggle: )];
    [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}

The navigation is ok, but I can not customise appearance of my Navigation bar:

I receive this:

enter image description here

, but I need something like this:

enter image description here

Any recommendations how to do that?

EDIT:

Ok, I managed to show proper size image, to change colour of the navigation bar, but I can not issue with status bar and navigation bar. When I set background colour of the navigation bar it fills also status bar. I see different solutions but they don't work or I don't understand them.

REMARK: I have several pages which are not part of Navigation controller in which my status bar is white. I need this also be the case for all my pages. (I need them to look like image 2, on which status bar is white and navigation section is blue).

Detect Unwind Event in Parent without Child Using Delegate

It is standard practice to use a parent delegate in a child view controller when performing segues, but I recently learned about the Law of Demeter from NSHipster and thought it would be ideal for the parent to know that its viewWillAppear was the result of returning from the child view controller. The child wouldn't have to know anything about or need to tell the parent anything.

Is there an elegant way to handle this?

Increasing height of UITableView when user drags button up

I have a UIView that takes up bottom half of the screen. It has a row of buttons on the top and then a UITableView that takes up the rest of the UIView. I want users to be able to click the button labeled "drag me" and be able to pull the UIView up to cover as much of the top half of the screen as they want.

More info on layout of UITableView and the UIView that contains it.

  • The UIView and the and UITableView are positioned using Auto Layout.
  • The UIView is pinned to a small UIView at bottom of screen.
  • The UITableView is pinned to the bottom of the UIView that contains it

I have successfully gotten the drag to increase or decrease size of UIView. By doing this it also moves the position of everything that it contains (ie top row of buttons and UITableView). I did by changing its frame (although originally positioned using Auto Layout) according to the translation of the y coordinate of the drag:

containerView.frame = CGRectMake(containerView.frame.minX, containerView.frame.minY + translation.y, containerView.frame.width, containerView.frame.height - translation.y)

However, I am unable to do that with UITableView. I have also tried creating a height constraint and changing that but that is also not working. This is what I have tried):

var constH:NSLayoutConstraint?

//in viewDidLoad        
constH = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tableView.frame.height)
tableView.addConstraint(constH!)


//in drag function
constH = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tableView.frame.height - translation.y)

I know the code is right for adding a constraint because I can put a constant there and it works (e.g. 50 changes it to that height).

The entire drag function is below:

func wasDragged(gesture: UIPanGestureRecognizer) {



    var yFromCenter: CGFloat = 0
    let translation = gesture.translationInView(self.view)
    var drag = gesture.view!
    var scale = min(200 / abs(yFromCenter), 1)
    yFromCenter += translation.y



    var yLimitTest = containerView.frame.minY + translation.y
    if yLimitTest < minimumY {

        drag.center = CGPoint(x: drag.center.x, y: drag.center.y + translation.y)
        gesture.setTranslation(CGPointZero, inView: self.view)
        drag.transform = CGAffineTransformScale(self.view.transform, scale, scale)

        //this IS working 
        containerView.frame = CGRectMake(containerView.frame.minX, containerView.frame.minY + translation.y, containerView.frame.width, containerView.frame.height - translation.y)

        //this doesn't work
        constH = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tableView.frame.height - translation.y)


        //this also doesn't work (but does for UIView containing the UITableView
        self.tableView.frame = CGRectMake(tableView.frame.minX, tableView.frame.minY + translation.y, tableView.frame.width, tableView.frame.height - translation.y)

    }
}

Constraints set but views not placed correctly

I'm having an issue with constraints. I set constraints on my UI elements that you can see below. For each I set x, y, and height/width for some. When I click "Update the Frames", everything is ok and the views are placed at the right place. But on the Preview (right window on the screenshot) and in the simulator, the views are not placed correctly and there is nothing on the screen. When I launch the app on the simulator, I have no warning in the debug console saying that there are constraints conflicts. Same in Xcode, no warning and no error.

Here are my View controller and the set constraints. You can see on the right, the preview for several devices.

xcode screenshot

Saving and Loading an NSMutableArray

I want my app to work so that when a user presses a "save" button, an NSMutableArray of strings (the array is called "names") inputted from a textfield will be saved. Naturally I also then want to be able to load the NSMutableArray any time I close/reopen the app.

Right now my save button is an IBAction "save". So in my implementation file I have:

- (IBAction)save:(id)sender
{ 
    NSArray *paths =  NSSearchPathforDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0]; 
    NSString *fileName = [NSString stringWithFormat:@"%@/myArray", docDir]; 
    [NSKeyedArchiver archiveRootObject:names toFile:fileName];
}

First of all, does this seem like it should work? Because multiple times my app crashed when I tried to then press the save button. Second am I right to be creating the file path in the IBAction? Or should I be creating it somewhere else (e.g. under viewDidLoad)?

Second, how and where should I be loading my saved NSMutableArray ("names")?

Many thanks!

Cant write data to plist file in - objective c

I'm trying to read and write data to my plist file, While the reading part goes well, the writing part does nothing.

I might be mistaken for the writing part - i can't see any changes in my file under my bundle - it is still empty after my changes, and when i close the app and open it again - i still see empty email address line.

The code for writing (and placing the plist in the document folder for future writings)

NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"userData.plist"];

NSLog(@"plist path %@",destinationPath);
if ([fileManger fileExistsAtPath:destinationPath]){
    NSLog(@"database localtion %@",destinationPath);
    //return;
}

NSString *sourcePath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"userData.plist"];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: sourcePath];
NSString *emailAddress = (NSString *)[dict objectForKey: @"emailAddress"];
if([emailAddress isEqualToString:@""])
{
    // Do stuff
}

And for writing

NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *doumentDirectoryPath =[pathsArray objectAtIndex:0];

NSString *destinationPath = [doumentDirectoryPath stringByAppendingPathComponent:@"userData.plist"];

NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile: destinationPath];

[plistDict setValue:@"myEmail@gmail.com" forKey:@"emailAddress"];
[plistDict writeToFile:destinationPath atomically: YES];

But as i said, nothing is changed in the file itself, and not even when i save, close the app and open it again (the string is always empty on my reading part)

Any help will be more than welcomed.

How do i draw a UIView to a CGContext without renderInContext when it is not attached to any hierarchy

I am drawing stuff onto a video frame and the best way i found is to get the CVImageBufferRef from the Video frame and then draw into/onto it like with any other CGContext drawing.

Now i have loads of UIViews that i simply create without adding them to any superview. I want these UIViews drawn without renderInContext because this would take me 1 second per frame or 30 sec rendertime per second of video.

If i use drawViewHierarchyInRect nothing is drawn.

If i use drawRect nothing is drawn and i get lots of invalid context errors

I am calling setNeedsDisplayand setNeedsLayout before and the Rects are all valid.

Same issue with non-custom UIViews like a UILabel.

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

   // Lock the image buffer
    CVPixelBufferLockBaseAddress(imageBuffer,0);



    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(CVPixelBufferGetBaseAddress(imageBuffer),
                                                     CVPixelBufferGetWidth(imageBuffer),
                                                     CVPixelBufferGetHeight(imageBuffer),
                                                     8,
                                                     CVPixelBufferGetBytesPerRow(imageBuffer),
                                                     colorSpace,
                                                     kCGBitmapByteOrder32Little |
                                                     kCGImageAlphaPremultipliedFirst);


    // now i want to draw my UIView


    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);



    // Unlock the image buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

Changing UIImageView dynamically

imagesArray is an array of UIImageViews

for (int i = 0; i < [imagesArray count]; i++) {                
    [[imagesArray objectAtIndex:i] setImage:[UIImage imageNamed:@"set-image.png"]];
}

This will always set the last or i(th) image correctly. It will not loop and change all the images I need. Is there another way to manage this?

How can I calculate the size of a UICollectionViewCell loaded from a xib with autolayout aspect ratio constraints?

I have a UICollectionViewCell that is loaded from a xib and stored in a property to help with calculating cell sizes for my collection view. The collection view always has only one column, so the cells vary in their widths based on the phone the user has (iphone 5/6/6+). The xib has an image view with an aspect ratio that must remain constant for all phone sizes.

The problem I run into stems from this configuration. I cannot seem to make the cell size the way I want based on a fixed width. My sizeForItemAtIndexPath: method looks like this:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.sizingCell.frame.size.width = self.flowLayout.fullViewSectionSize.width;
    [self configureCell:self.sizingCell atIndexPath:indexPath];
    [self.sizingCell setNeedsLayout];
    [self.sizingCell layoutIfNeeded];
    CGSize size = [self.sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size;
}

I'm doing what I've read I'm supposed to for dynamic size calculations with an off-screen cell, but the problem is that when layoutIfNeeded is called, I get an unsatisfiable constraint exception with my constraints and an extra constraint that sets the height of the cell to be the height of it as defined in the xib. The system never breaks this extra height constraint I did not add, so the height of the cell is always this incorrect height of the view at design time in the xib.

Can I somehow remove this extraneous constraint that causes this to not work? Is there some other setting to set here that does what I need? I've tried turning off translatesAutoResizingMaskIntoConstraints to no avail as well. How can I make a xib-loaded cell figure out it's size based on constraints involving aspect ratios?

iOS: How do I draw a line (UIBezierpath or otherwise) that fades over time, and interacts with views as it touches them?

For example:

I draw the orange line below with my finger, as it touches the blue squares, they light up.

I can draw a line using UIBezierPath from StackOverflow questions / tutorials I found, but I have no idea how to make it fade away or interact with other views.

This is not a for a game, just a regular iOS app. I'm not sure if that changes things.

Any ideas?

Example Image

Center UILabel Subview

I have a UIImageView as the background view of my table view. When there is no data for the table, I am adding a UILabel as a subview of the image view. I am having trouble getting the label centered though. The label is always off to the right.

UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:self.tableView.frame];
    backgroundImageView.image = [UIImage imageNamed:@"background"];
    backgroundImageView.center = self.tableView.center;

    self.noLocationsLabel = [[UILabel alloc]initWithFrame:backgroundImageView.frame];
    self.noLocationsLabel.center = backgroundImageView.center;
    self.noLocationsLabel.text = @"No saved locations";
    self.noLocationsLabel.textAlignment = NSTextAlignmentCenter;
    self.noLocationsLabel.textColor = [UIColor blackColor];
    self.noLocationsLabel.font = [UIFont fontWithName:@"Chalkboard SE" size:24.0];

self.tableView.backgroundView = backgroundImageView;

if (self.locationsArray.count == 0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;

        [self.tableView.backgroundView addSubview:self.noLocationsLabel];
        self.tableView.userInteractionEnabled = NO;
    }

navigationItem titleview align center between buttons

I have the code likes, in the title bar I am having 3 buttons, left search button, right camera button and option button, in between I am having title.

What I want to do is, I want to display the title centered between the search button and Camera button, can anyone help me how to do this.

//Left Button
UIBarButtonItem *leftSearch = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_search"] style:UIBarButtonItemStyleBordered target:self action:@selector(gotoSearch)];

leftSearch.imageInsets = UIEdgeInsetsMake(0, -5.0f, 0, 0);

[leftSearch setTintColor:[UIColor whiteColor]];
/////////

//Right Button -- First Camera
UIBarButtonItem *rightCamera = [[UIBarButtonItem alloc]
                                initWithImage:[UIImage imageNamed:@"icon_camera"]
                                style:UIBarButtonItemStyleBordered
                                target:self
                                action:@selector(gotoPhotoGallery)];
[rightCamera setTintColor:[UIColor whiteColor]];
rightCamera.imageInsets = UIEdgeInsetsMake(0, 0, 0, -59.0f);
///////////////////

//Right second Button -- for options menu
UIBarButtonItem *rightMenu = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header_option"] style:UIBarButtonItemStyleBordered target:self action:@selector(gotoPhotoGallery)];
[rightMenu setTintColor:[UIColor whiteColor]];
rightMenu.imageInsets = UIEdgeInsetsMake(0, 0, 0, 5.0f);
///////////////////

NSArray *buttons = @[rightMenu, rightCamera];

self.navigationItem.rightBarButtonItems = buttons;

[[self navigationItem] setLeftBarButtonItem:leftSearch];

//Title Label

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Museo Sans" size:20];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = LoginUserName;
self.navigationItem.titleView = label;
[label sizeToFit];

Why is this NSString null in a FireBase query block?

I can't figure out why this string is null inside the FQuery block. My app keeps crashing when I build the dailyLog MutableDictionary at the user key;

NSString *userID = [self.userProfile objectForKey:@"userID"];
self.logFirebase = [[Firebase alloc] initWithUrl:@"http://ift.tt/1zK8jF4"];
[[[self.logFirebase queryOrderedByChild:@"userID"] queryEqualToValue:userID] observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

    FQuery *queryRef = [[self.logFirebase queryOrderedByChild:@"date"] queryEqualToValue:[df stringFromDate:[NSDate date]]];
    [queryRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

        NSLog(@"value:%@", snapshot.value);
        if (![snapshot.value isEqual:[NSNull null]]) {
            self.dailyLog = snapshot.value;
        }else{
            self.dailyLog = [[NSMutableDictionary alloc] init];
            NSLog(@"users Profile:%@",self.userProfile); //This is working fine, I see data and I'm using the right keys

            [self.dailyLog setObject:[df stringFromDate:[NSDate date]] forKey:@"date"];
            [self.dailyLog setObject:userID forKey:@"user"];
            [self.dailyLog setObject:[NSNumber numberWithInt:450] forKey:@"calories"];


            [[self.logFirebase childByAutoId] setValue:self.userProfile];

        }

    }];

}];

EDIT: When I log self.userProfile, I get the proper info I want. But when I log the userID itself from within the FQuery block, it's null

How to authenticate IOS app without displaying Auth 2.0 VIewcontroller?

Here , i want to get 'access token' for iPhone application without displaying Auth2.0 view controller. Authenticate the app and get access token and refresh token. Help me to solve this problem. Remember I do not want to show UI of Google. Just make two field username and password . With Log in button authenticate the app and get tokens.

Error saving core data object

I am quite confused about one error I am receiving when saving an object. I am receiving the following error (when I print out the detailed description):

2015-05-08 08:19:51.589 Br[11240:208443] Core Data Save Error

                           NSValidationErrorKey
activityObject

                           NSValidationErrorPredicate
(null)

                           NSValidationErrorObject
<BRActivity: 0x7deb2aa0> (entity: BRActivity; id: 0x7deb2780 <x-coredata:///BRActivity/t86C0E8CD-2B6C-4AF7-986A-4797B7BEFDF5> ; data: {
activities =     (
);
activityObject = nil;
activityType = 0;
body = "Someone left a comment on your post.";
timestamp = "2015-05-08 04:24:46 +0000";
uuidString = "c6a06b45-e2d5-45bd-9f64-20b13ac87526";
})

                           NSLocalizedDescription
The operation couldn’t be completed. (Cocoa error 1570.)
2015-05-08 08:19:51.590 Br[11240:208443] Core Data Save Error

So from looking on the internet, it seems to be a relationship problem. So a Br post has a relationship called activities relationship, the inverse of which is an activity object. Now that, as we can see from the error, is nil. So what kind of solution are we looking at here... Is there a way to make the relationship "optional" (ok to be nil!) or should I add an activity object? I really don't want to break anything here so if there's a subtle solution let me know. Thanks a bunch guys!

Also here is the method surrounding the save:

 - (void)importArray:(NSArray *)array entityName:(NSString *)entityName attributeName:attributeName error:(NSError *__autoreleasing *)error {
NSParameterAssert(array);
NSParameterAssert(entityName);

[self.context performBlockAndWait:^{
    for (NSDictionary *jsonDictionary in array) {
        NSManagedObject *managedObject = [NSManagedObject upsertWithContext:self.context entityName:entityName dictionary:jsonDictionary attributeName:attributeName error:error];
        if (nil == managedObject) {
            if ([self.context hasChanges]) {
                [self.context rollback];
            }
            return;
        }
    }

    if ([self.context hasChanges]) {
        if (![self.context save:error]) {
            NSError *err = *error;


            NSDictionary *userInfo = [err userInfo];
            if ([userInfo valueForKey:@"NSDetailedErrors"] != nil) {
                // ...and loop through the array, if so.
                NSArray *errors = [userInfo valueForKey:@"NSDetailedErrors"];
                for (NSError *anError in errors) {

                    NSDictionary *subUserInfo = [anError userInfo];
                    subUserInfo = [anError userInfo];
                    // Granted, this indents the NSValidation keys rather a lot
                    // ...but it's a small loss to keep the code more readable.
                    NSLog(@"Core Data Save Error\n\n \
                          NSValidationErrorKey\n%@\n\n \
                          NSValidationErrorPredicate\n%@\n\n \
                          NSValidationErrorObject\n%@\n\n \
                          NSLocalizedDescription\n%@",
                          [subUserInfo valueForKey:@"NSValidationErrorKey"],
                          [subUserInfo valueForKey:@"NSValidationErrorPredicate"],
                          [subUserInfo valueForKey:@"NSValidationErrorObject"],
                          [subUserInfo valueForKey:@"NSLocalizedDescription"]);
                }
            }


            NSLog(@"Error: %@", err.localizedDescription);
        }
        return;
    }
}];
}

iOS Add Label on TableCell at Indexpath

I'm trying to present a label every time the user double taps on my cell. I can detect the taps and I can execute code from them but I'm having an issue with the labels. For some reason the labels are being added two sometimes three cells below the one it should be added on. I need the label to be added on the cell that was tapped, shouldn't be to hard to do.

Here is my code, thanks in advance.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    static NSString *CellIdentifier = @"cell";

    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (nil == cell)
    {
        cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    PFObject *tempObject = [_myArray objectAtIndex:indexPath.row];
    NSString *currentUser = [[PFUser currentUser]username];

    //NSLog(@"%@",tempObject);
    NSArray *test = [tempObject valueForKey:@"Like"];
    //NSLog(@"%lu",(unsigned long)test.count);


    NSTimeInterval now = [[[NSDate alloc] init] timeIntervalSince1970];
    if ((now - lastClick < 0.3) & [indexPath isEqual:lastIndexPath]) {

        //cell.test.hidden = NO;
        CGRect frame = CGRectMake(0,0, 80, 40);

        UILabel *label1 = [[UILabel alloc]init];

        label1.frame = frame;

        label1.text = @"first label";
        [cell.contentView addSubview:label1];


        if ([test containsObject:currentUser]) {
            NSLog(@"1");

            [tempObject removeObject:currentUser forKey:@"Like"];
            [tempObject saveInBackground];

        }else {
            NSLog(@"2");
            [tempObject addUniqueObject:currentUser forKey:@"Like"];
            [tempObject saveInBackground];
        }

    }

    lastClick = now;
    lastIndexPath = indexPath;

}

Translate computed property from Category into Swift Extension

I have the following objective-c category:

@implementation UINavigationBar (Awesome)
static char overlayKey;
static char emptyImageKey;

- (UIView *)overlay
{
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay
{
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

I tried to translate it into a Swift extension like this:

var AssociatedObjectHandle: UInt8 = 0

extension UINavigationBar {

  var stringProperty:Character {
    get {
      return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! Character
    }
  }


  func setOverlay(overlay: UIView) {
    objc_setAssociatedObject(self, &AssociatedObjectHandle, overlay, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))

  }

}

It looks strange because I created a global variable AssociatedObjectHandle and I am not sure what the Character actually does?

Is this the correct way to translate the computed property?

UILabel flicker when changing font dynamically on UITableViewCell

tableView.estimatedRowHeight = 90.0
tableView.rowHeight = UITableViewAutomaticDimension
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any
    let cell = self.tableView.dequeueReusableCellWithIdentifier("DetailCell") as DetailCell

    var detail : Detail
    detail = Details[indexPath.row]

    var paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 15
    paragraphStyle.alignment = NSTextAlignment.Right

    var attrString = NSMutableAttributedString(string: detail.detailText)
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

    var fontName = cell.myLabel.font.fontName

    cell.myLabel.font = UIFont(name:fontName, size: pointSize)
    cell.myLabel.attributedText = attrString


    return cell
}

pointSize changes as the user pinches (used UIPinchRecognizer) the default pointSize of myLabel is 17. The code works perfectly when pinched to increase or decrease the pointSize. But while scrolling first the default size is applied and then increased or decreased size due to this the cells are giving a flicker effect while scrolling.

How do I avoid this? Is there any sample example already done for UITableViewCells

Unable to get custom MKAnnotationView callout to appear

I'm building an OSX application that uses Mapkit, and I'm trying to get a callout to appear when I click on an MKAnnotationView on my map. To do this I'm implementing the MKMapViewDelegate, and the following function :

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[LocationPin class]]) {
    LocationPin *returnPin = (LocationPin *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"LocationPin"];
    if (!returnPin){
        returnPin = [LocationPin createLocationPinForMapView:mapView annotation:annotation];
    }
    returnPin.title = annotation.title;
    NSButton *rightButton = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 0.0, 100.0, 80.0)];
    [rightButton setTitle:@"Info"];
    [rightButton setBezelStyle:NSShadowlessSquareBezelStyle];
    returnPin.annotation = annotation;
    returnPin.canShowCallout = YES;
    returnPin.rightCalloutAccessoryView = rightButton;
    return returnPin;
    }
    return nil;
    }

The function runs fine everytime I put a new pin down, and I made sure the titles of the pins are not empty or null, but the callout still is not showing up. Anybody have any ideas?

EDIT: After looking through Anna's response, I realized I misunderstood how to implement the MKAnnotation protocol. I've deleted my LocationPin class, which inherited from MKAnnotationView, and instead added the following class to represent my custom MKAnnotation, with a class inside of it to generate a custom MKAnnotationView:

@implementation LocationAnnotation:

-(id)initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location     {
    self = [super init];

    if(self) {
    _title = newTitle;
    _coordinate = location;
    }

    return self;
}

- (MKAnnotationView *)annotationView {

    MKAnnotationView *annotationView = [[MKAnnotationView alloc]initWithAnnotation:self reuseIdentifier:@"LocAnno"];
    annotationView.enabled = YES;
    annotationView.canShowCallout = YES;
    annotationView.image = [NSImage imageNamed:@"dvd"];

    NSButton *rightButton = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 0.0, 100.0, 80.0)];
    [rightButton setTitle:@"Info"];
    [rightButton setBezelStyle:NSShadowlessSquareBezelStyle];

    annotationView.rightCalloutAccessoryView = rightButton;

    return annotationView;
}

@end

I've also changed the MKMapViewDelegate function the following way now:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[LocationAnnotation class]]) {

        LocationAnnotation *anno = (LocationAnnotation *)annotation;
        MKAnnotationView *returnPin = [mapView dequeueReusableAnnotationViewWithIdentifier:@"LocAnno"];
        if (!returnPin){
            returnPin = anno.annotationView;
        }
        else {
            returnPin.annotation = annotation;
        }
        return returnPin;
    }
    return nil;
}

But the callout still is not appearing. Any help is appreciated.

Edit 2: As requested, LocationAnnotation.h:

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface LocationAnnotation : NSObject <MKAnnotation>

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (copy, nonatomic) NSString *title;

-(id)initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location;
-(MKAnnotationView *)annotationView;



@end

Objective-C Refresh Table View (RSS/xCode)

I'm trying to implement a pull-to-refresh feature on my RSS feed table. The list pulls normally when loading the app, but I essentially need to replicate that for the pull-down.

Could anyone help as to why the code isn't working?

#import "RSSTableViewController.h"
#import "RSSDetailViewController.h"

@interface RSSTableViewController () {


    NSXMLParser *parser;
    NSMutableArray *feeds;
    NSMutableDictionary *item;
    NSMutableString *title;
    NSMutableString *link;
    NSString *element;

}

@end

@implementation RSSTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // RSS Settings
    feeds = [[NSMutableArray alloc] init];
    NSURL *url = [NSURL URLWithString:@"http://ift.tt/1AKPEEt"];
    //
    // BBC RSS - http://ift.tt/1Rjha6i
    //
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];

    // Pull to Refresh
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:refreshControl];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];

}


    //Refresh handler
- (void)refresh:(UIRefreshControl *)refreshControl {


    [self.rssTableView reloadData];
    [refreshControl endRefreshing];
}




- (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 feeds.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey:@"title"];

    return cell;
}



- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    element = elementName;

    if ([element isEqualToString:@"item"]) {

        item = [[NSMutableDictionary alloc]init];
        title = [[NSMutableString alloc]init];
        link = [[NSMutableString alloc]init];
    }


}



- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([elementName isEqualToString:@"item"]) {

        [item setObject:title forKey:@"title"];
        [item setObject:link forKey:@"link"];

        [feeds addObject:[item copy]];

    }

}



-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    }
    else if ([element isEqualToString:@"link"]) {
        [link appendString:string];

    }

}


-(void)parserDidEndDocument:(NSXMLParser *)parser {

    [self.tableView reloadData];

}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSString *string = [feeds[indexPath.row] objectForKey:@"link"];
        [[segue destinationViewController] setUrl:string];

    }

}



@end

I'm really stuck here and need to know to move on! Please do help!

EXEC_BAD_ACCESS on dequeuing cell from UICollectionView

I have a problem when dequeuing a UICollectionView cell from the storyboard. I have a view controller with a collection view as one of the subviews. The VC is set as the collection view's data source and delegate. The collection view has a couple of prototype cells with identifiers set.

When doing this:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.sizingCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"CellId" forIndexPath:nil];
}

I get an EXEC_BAD_ACCESS on the self.sizingCell line. Interestingly, when I created a new test project with a view controller containing a collection view and did the same thing in viewDidLoad, the collection view's cell was created with no issues. Did anyone else run into a similar issue?

Black bar over a TableView just above TabBar

I have a UITableView with cells which perform a segue to an other simple detail view. The UITableView and detail view are embed in a Navigation Controller.

On my UITableView I put a UISearchController bar folowing this tutorial: http://ift.tt/1dStQBT

So now, I have the following graphic problem: When I perform a segue by tapping a cell after having make a research, I arrive to my detail view. But when I tap the Back button in the Navigation Bar, a mysterious black bar appears just above the TabBar. When the animation is over, the black bar disappears.

enter image description here

But when I tap the return button from the detail view without having done a research to arrive at this detail view, there is no black bar.

I can't understand why there is that black bar. I just note the black bar's height is equal to the TabBar's height. Maybe a link ?

UITableView powered by FetchedResultsController with UITableViewAutomaticDimension - Cells move when table is reloaded

Current set up:

TableView with automatically calculated heights:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 152.0;
self.tableView.estimatedSectionHeaderHeight = 50.0;

Whenever the fetched results controller updates its data the tableview is reloaded:

 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView reloadData]; 
}

The cell is configured using a Xib. The first label is pinned to the top of the cell, each following label is pinned to the top of the label above it and the label at the bottom is pinned to the bottom of the cell.

The Issue:

Each time i set a "Favourite" property on an item in the table view, the fetched results controller is fired to reload the table and the scroll position is changed. It is this change in the scroll position that i am trying to fix.

Additional Info

If i use fixed cell heights it resolves the issue BUT i require UITableViewAutomaticDimension because the first label can wrap over two lines and the remaining labels may or may not be present.

Example

Note - As i select the Fav button it sets the fav property in Core data and reloads the table. Why is the table jumping around?

enter image description here

How do I add a date of birth UIDatePicker to UITextField?

I request the users date of birth on the sign up screen of my application. I can't figure out how to get a date of birth UIDatePicker to display. I tried using the following code but it only displays the date and time:

 UIDatePicker *dp = [[UIDatePicker alloc]init];
_textBirthday.inputView = dp;

Also, how would I set it so it only accepts users born after a certain year?

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;
}

Comparing UI object in ios

I am making a super class to TableView, I will have static TextView in it and also I have TextView in cells.

Then I starting edit my TextView in Cell I assign it to static property of TableView.

Now I need go thought cells subviews, compare 2 textView (static and textView in cell) and find cell.

How can I compare 2 textViews?

I can not compare its texts because then some text did typed I lost event.

Setting Device Independent RGB on iOS

I am detecting the rgb of a tapped pixel. Different iPads return slightly different RGB values. I maintain a plist of the different values returned per device and when the app opens it determines the device I am on and uses appropriate values. This is a terrible solution - but it does work.

I now want to fix this properly so I dived into colorspace on iOS. It seems I can use CGColorSpaceCreateCalibratedRGB to set a standard RGB regardless of device so the values returned are the same? Or do I need to convert the

However, I do not know any of the values needed to create a standard color space across devices so my pixel color return values are always the same - or if this is possible.

Some current example return values: iPad 2 r31 g0 b133 a1 iPad Air r30 g0 b132 a1

Can anyone help 'normalize' the pixel return value in a device independent way?

- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
UIColor* color = nil;
CGImageRef inImage = self.image.CGImage;
// Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpha, Red, Green, Blue
CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
if (cgctx == NULL) { return nil; /* error */ }

size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}}; 

// Draw the image to the bitmap context. Once we draw, the memory 
// allocated for the context for rendering will then contain the 
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, inImage); 

// Now we can get a pointer to the image data associated with the bitmap
// context.
unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL) {
    //offset locates the pixel in the data from x,y. 
    //4 for 4 bytes of data per pixel, w is width of one row of data.
    int offset = 4*((w*round(point.y))+round(point.x));
    int alpha =  data[offset]; 
    int red = data[offset+1]; 
    int green = data[offset+2]; 
    int blue = data[offset+3]; 
    ////NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
    //NSLog(@"colors: RGB A %i %i %i  %i",red,green,blue,alpha);
    color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}


// When finished, release the context
CGContextRelease(cgctx); 
// Free image data memory for the context
if (data) { free(data); }

return color;

}

  • (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {

    CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow;

    // Get image width, height. We'll use the entire image. size_t pixelsWide = CGImageGetWidth(inImage); size_t pixelsHigh = CGImageGetHeight(inImage);

    // Declare the number of bytes per row. Each pixel in the bitmap in this // example is represented by 4 bytes; 8 bits each of red, green, blue, and // alpha. bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

    // Use the generic RGB color space. colorSpace = CGColorSpaceCreateDeviceRGB();

    if (colorSpace == NULL) { fprintf(stderr, "Error allocating color space\n"); return NULL; }

    // Allocate memory for image data. This is the destination in memory // where any drawing to the bitmap context will be rendered. bitmapData = malloc( bitmapByteCount ); if (bitmapData == NULL) { fprintf (stderr, "Memory not allocated!"); CGColorSpaceRelease( colorSpace ); return NULL; }

    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here by CGBitmapContextCreate. context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst); if (context == NULL) { free (bitmapData); fprintf (stderr, "Context not created!"); }

    // Make sure and release colorspace before returning CGColorSpaceRelease( colorSpace );

    return context; }

How to Recieve iOS Screen Lock Status

I am a noob just learning to code, so please bear with me.

I am trying to implement a location tracking application and here is my problem. I want to stop GPS updates when iPhone is locked or went into sleep mode.

I have used this discussion as reference point. This is what I have so far.

LockNotifierCallback.h

    #import <Foundation/Foundation.h>
@import CoreFoundation;

@interface LockNotifierCallback : NSObject

+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;

- (void)registerForDeviceLockNotifications;

@end

LockNotifierCallback.m

#import "LockNotifierCallback.h"
@import CoreFoundation;

static void lockcompleteChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    CFStringRef nameCFString = (CFStringRef)name;
    NSString *notificationName =  (__bridge NSString*)nameCFString;
    NSLog(@"Darwin notification NAME = %@",name);

    NSString *timerStatus = @"No Change";
    if ([notificationName isEqualToString:@"com.apple.springboard.lockcomplete"]) {
        timerStatus = @"Yes";
    } else if ([notificationName isEqualToString:@"com.apple.springboard.lockstate"]) {
       timerStatus = @"No";
    }

    NSLog(@"success");
}

@implementation LockNotifierCallback;

+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc {
    return lockcompleteChanged;
}

- (void)registerForDeviceLockNotifications;
{
    NSLog(@"registering for device lock notifications");

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    lockcompleteChanged, // callback
                                    CFSTR("com.apple.springboard.lockcomplete"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    lockcompleteChanged, // callback
                                    CFSTR("com.apple.springboard.lockstate"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}


@end

Xcode compiles this without any error but I don't think it is working as I don't see any logs in Console when I run the app in simulator.

Its a SWIFT project and I have #import "LockNotifierCallback.h" in my bridging header.

Please answer this in detail as I am still learning to code.

Appreciate your help.

EDIT

I am using Objective C only to receive Darwin notification for lockstate (device sleep / awake) to optimize battery life as my app will run in the background, apart from this I am planning to implement location tracking and other functions in SWIFT.

JSON conversion issue in iOS

I have a json string and another one. i have to append together, send to server and get user id. I am stuck in d middle. Appended string is not getting converted to NSURL.


Here is my code.

- (void)convertingstringtojsondata
{
    NSArray *components = [[NSArray alloc]initWithObjects:ismunicipality,mobilenumberstring,placestring,namestring,  nil];
    NSArray *keys = [[NSArray alloc]initWithObjects:@"is_municipality",@"ph_nbr",@"place",@"reg_name", nil];
    NSLog(@"%@",components);

    NSDictionary *dict = [[NSDictionary alloc]initWithObjects:components forKeys:keys];

    NSLog(@"dict %@", dict);

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:0
                                                         error:nil];
    NSLog(@"JSON DATA %@", jsonData);

    jsonData= jsonData;

  JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

    NSLog(@"JSON STRING%@",JSONString);
}
-(void)sendjsonforregistration
{
 [self convertingstringtojsondata];

    registerwithserverstring = [[NSMutableString alloc]initWithString:@"http://ift.tt/1PtRVKM"];
    [registerwithserverstring appendString:JSONString];

    NSLog(@" appended string %@", registerwithserverstring);

    NSURL *registerURL = [NSURL URLWithString:registerwithserverstring];

    NSLog(@"register URL%@", registerURL);

NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:registerURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData * data, NSError * error) {
    NSData * jsonData1 = [NSData dataWithContentsOfURL:registerURL];

    NSLog(@"%@", jsonData1);

    dataDictionary1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:0 error:&error];

   NSLog(@"DATA DICTIONARY %@", dataDictionary1);

}];
}


Problem:- The registerURL shows null value...

Double quotes not showing up in string value inside NSMutableDictionary [duplicate]

I'm trying to post some json content to server using REST apis. On POST request, server is accepting the content value like the one given below in body

{
    "value" = "MyDataValue";
}

But after creating the web request, when I try to log the POST data, what I'm getting in console output is

{
    "value" = MyDataValue;
}

Note: No double quotes around MyDataValue.

On trying the same request with double quotes on chrome poster returns success and without double quotes returns same error in poster also. So I guess adding double quotes would solve the issue.

Here is the code I used for creating the NSDictionary

NSMutableDictionary *parameterDict = [NSMutableDictionary new];  
[parameterDict setObject:@"MyDataValue"forKey:@"value"];

Also, tried adding double quotes using escape character, but returns in 2 double quotes which also returns error. So any other alternative solution would be helpful.

Thanks.

Cropping AVCaptureVideoPreviewLayer output to a square

I am having issues with my AVCaptureVideoPreviewLayer method when grabbing a cropped UIImage of the viewable screen. Currently it is working but not outputting the correct crop that I require.

I am trying to output a square but it (by the looks of it) seems to be giving the full height and compressing the image.

The before image shows the LIVE screen and the after image shows the image once the capture button has been pressed. You can see that it has been changed vertically to fit the square but the height hasn't been cropped vertically.

enter image description here

Capture Image Code

[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

    if (imageSampleBuffer != NULL) {

        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
        [self processImage:[UIImage imageWithData:imageData]];

    }
}];

Cropping code

- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate

        haveImage = YES;

    CGRect deviceScreen = _previewLayer.bounds;
    CGFloat width = deviceScreen.size.width;
    CGFloat height = deviceScreen.size.height;

    NSLog(@"WIDTH %f", width); // Outputing 320
    NSLog(@"HEIGHT %f", height); // Outputting 320

    UIGraphicsBeginImageContext(CGSizeMake(width, width));
    [image drawInRect: CGRectMake(0, 0, width, width)];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGRect cropRect = CGRectMake(0, 0, width, width);

    CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);

    CGImageRelease(imageRef);

    [captureImageGrab setImage:[UIImage imageWithCGImage:imageRef]];

}

Looking for a framework to add a moveable view in the screen

I have to include to my App a little view with the same behaviour that in FaceTime. When you are having a video call in FaceTime appear a little view with the streaming video of the person who you are talking. I am looking for a framework that let me have a view that it can be moved around the screen like the little view in FaceTime.

Does anyone know of any framework to do this?

Thank you

Xcode: Copy files from one Project to another in same workspace

I am currently working on legacy code for an iPhone application. Someone has implemented a feature in the iPhone and now I am trying to implement it into iPad.

To start with I have decided to drag the files from the iPhone project into the iPad and get it working. Then I am going to find a solution where by both projects can share the same code.

However I have copied the files from the iPhone project into the ipad project and have a problem with the xib. The outlets are still referencing the iPhone version.

So when I remove the IBOutlets from the iPad version the connections still remain because the iPhone xib has not been touched. However when I remove the connections from the iphone project, it also removes the outlets from the ipad version.

These are both separate projects within the same workspace.

I am not sure why this is happening and also is there a way around copy the files without the file referencing the other project?

Blank Page in UIView

i created my simple app with a web view but it doesn't appear. Only blank page. My .xib contains the UIWebView My file ViewController.h:

#import <UIKit/UIKit.h>

@interface TestAViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIWebView *webview;

@end

My file ViewController.m:

#import "TestAViewController.h"

@interface TestAViewController ()

@end

@implementation TestAViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        // Custom initialization
    }
    
    return self;
}

- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.
    
    //load url into webview
    NSString *strURL = @"http://www.google.it";
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [self.webview loadRequest:urlRequest];
    
    
}

@end

Why this? Thanks

How to get actual first day of the month, possible with my time zone?

I'm trying to get the first day of the month, but I'm getting the UTC value. I think I need my locale date instead?

enter image description here

How to check if ios device is stationary?

I am working on a augmented reality app which uses openCV camera to match templates. Since too much processing is required for matching templates I want to run matching template only when the device is stationary for a couple of seconds.

Help will be highly appreciated... thanks

objective c Nsstream connect to multiple servers at a time using sockets

I am creating a socket based Ios app using objective c, now my requirement is to connect to two servers at the same time, i am using NSInputStream and NSOutputStream, now i am able to connect to first server and can send and receive data with that server using

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

delegate method but now i have to connect with second server at the same time, means connecting with two server at the same time, please guide me in this.

Changing Philips Hue Brightness with a UISlider Objective C

I am building an app that controls three philips hue RGB LED bulbs. I want to be able to change the brightness using the UISlider. Currently I have a UISlider that calls a method upon each change, however, this method far exceeds the philips hue bridge's 10 commands per second limitation. Here is the method I call upon a change in the UI slider.

- (void) changeBulbBrightness: (NSNumber *)currentBrightness
{
    NSTimeInterval timeInterval = [self.timeLastCommandSent timeIntervalSinceNow];
    NSLog(@"Time Since Last command: %f", timeInterval);
    if (timeInterval < -0.3)
    {
        NSLog(@"COMMAND SENT!!!!");
        PHBridgeResourcesCache *cache = [PHBridgeResourcesReader readBridgeResourcesCache];
        PHBridgeSendAPI *bridgeSendAPI = [[PHBridgeSendAPI alloc] init];
        for (PHLight *light in cache.lights.allValues)
        {
            PHLightState *lightState = light.lightState;
            //PHLightState *lightState = [[PHLightState alloc] init];
            if (lightState.on)
            {
                [lightState setBrightness:currentBrightness];
                // Send lightstate to light


     [bridgeSendAPI updateLightStateForId:light.identifier withLightState:lightState completionHandler:^(NSArray *errors) {
                /*if (errors != nil) {
                    NSString *message = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"Errors", @""), errors != nil ? errors : NSLocalizedString(@"none", @"")];
                    if (self.loggingOn)
                    {
                        NSLog(@"Brightness Change Response: %@",message);
                    }
                }
                 */
            }];
        }
        self.timeLastCommandSent = [[NSDate alloc]init];
    }
}
self.appDelegate.currentSetup.brightnessSetting = currentBrightness;
NSLog(@"Brightness Now = %@", currentBrightness);

I've tried making a timer to limit the amount of commands to 10 per second but the bridge still acts the same way it does when it is overwhelmed with commands (stops acceptance of all commands). Any help or direction would be greatly appreciated. Thanks in advance!

iPhone app on iPad: drawViewHierarchyInRect causes glitch

Running an iPhone app on iPad (iOS 8), using drawViewHierarchyInRect to take a snapshot and do a custom animation between two view controllers. It all runs fine on iPhones but when the app is on iPad (not a universal app, iPhone only) you can see a brief glimpse of a bad snapshot when the animation starts. Basically it seems to take a snapshot of the whole iPad screen, including the black edges, rather than just the simulated iPhone screen. The app also hides the status bar but you can see the status bar in the brief glimpse which means it's probably some kind of bug in iOS as the iPad always shows the status bar for iPhone apps at the top of the screen.

Here's the snapshot code;

UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:update];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Incidentally the flash also occurs when using Airplay to show the app on Apple TV.

Get WatchKit interface controller instances created with presentControllerWithNames:contexts:

I'm presenting a page based modal using [self presentControllerWithNames:self.controllerNames contexts:self.controllerContexts];, where controllerNames is just an NSArray of NSStrings containing my interface controllers names. The problem is that I would like to access the created controllers.

The documentations says that

WatchKit loads and initializes the new interface controllers and animates them into position on top of the current interface controller.

but I would like to have a reference to them, in order to call the becomeCurrentPage method from outside.

So, I would like to be able to save those controllers after they are created in a list, and programmatically change the page using something like [self.controllers[2] becomeCurrentPage].

Mutating method sent to immutable object closes app

In my code ,when the user completes a level, it unlocks the next level (out of a total of 15 levels).

However, I have noticed that, when I complete the level, first time, it works, however, when I go back to it and try again, it crashes with this error;

[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object

The code part is this;

//Unlock Next Level
                if (levelNumber != 15) {
                    [m_appDelegate.levels replaceObjectAtIndex:levelNumber withObject:[NSNumber numberWithBool:NO]];
                    [m_appDelegate saveLevels];
                }

If I remove this line;

[m_appDelegate.levels replaceObjectAtIndex:levelNumber withObject:[NSNumber numberWithBool:NO]];

Then the app does not crash, but of course, it does not unlock any further levels.

Some references below that may help;

int levelNumber;
@property (nonatomic, readwrite) int levelNumber;


- (void) actionLockedLevel:(id)sender {
    selectedLevel = ((CCNode*)sender).tag;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Level Locked" message:@"Level is locked. Pass the previous level first." delegate:nil cancelButtonTitle:@"No" otherButtonTitles:nil];
    [alert show];
}

- (void) actionUnlockedLevel:(id)sender {

    CCScene *scene = [CCScene node];
    TimedLevel *layer = [TimedLevel node];
    layer.levelNumber = ((CCNode*)sender).tag;
    [scene addChild:layer];


    [[CCDirector sharedDirector] replaceScene:scene];
}

How to remove black edge on UIImageView with rounded corners and a border width?

I have the following code to make the UIImageView in each of my UITableView's cells have rounded corners:

- (void)awakeFromNib
{
    // Rounded corners.
    [[cellImage layer] setCornerRadius:([cellImage frame].size.height / 2)];
    [[cellImage layer] setMasksToBounds:YES];
    [[cellImage layer] setBorderColor:[[UIColor whiteColor] CGColor]];
    [[cellImage layer] setBorderWidth:3]; // Trouble!
}

I want the images to have a bit of a gap between them, and figured I could make use of the border width to make that happen. Below is an image of what actually happened:

list of users with badly rendered rounded corners

It's that faint black border that I want to know how to get rid of. I'd like to think there's a way of doing it using border width. If not, the best approach might be just to resize the image itself and just set the border width to be 0.

OCLint for Xcodebuild Shell Error

I am getting these error after creating a new Aggregate target with below script:

error: oclint not found, analyzing stopped Command /bin/sh failed with exit code 1

Run Script Shell: /bin/sh

Script:

source ~/.bash_profile

hash oclint &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "oclint not found, analyzing stopped"
exit 1
fi

cd ${TARGET_TEMP_DIR}

if [ ! -f compile_commands.json ]; then
echo "[*] compile_commands.json not found, possibly clean was performed"
echo "[*] starting xcodebuild to rebuild the project.."
# clean previous output
if [ -f xcodebuild.log ]; then
rm xcodebuild.log
fi

cd ${SRCROOT}

xcodebuild clean

#build xcodebuild.log
xcodebuild | tee ${TARGET_TEMP_DIR}/xcodebuild.log
#xcodebuild <options>| tee ${TARGET_TEMP_DIR}/xcodebuild.log

echo "[*] transforming xcodebuild.log into compile_commands.json..."
cd ${TARGET_TEMP_DIR}
#transform it into compile_commands.json
oclint-xcodebuild

echo "[*] copy compile_commands.json to the project root..."
cp ${TARGET_TEMP_DIR}/compile_commands.json ${SRCROOT}/compile_commands.json

fi

echo "[*] starting analyzing"
cd ${TARGET_TEMP_DIR}
oclint-json-compilation-database | sed 's/\(.*\.\m\{1,2\}:[0-9]*:[0-9]*:\)/\1 warning:/'

Do I have to change xcode default script to bash? how to do it? Thanks.

SLComposeViewController appears slowly

SLComposeViewController takes 3-4 seconds to appear after presenting it. But presentViewController:(UIViewController *) animated:(BOOL) completion:^(void)completion methods completion block gets called immediately. So even if I use a loading indicator it disappears in a blink. The related code is below. Btw I tried dispatch_async it didn't work.

How can I speed up the process do you have any ideas?

SLComposeViewController *shareView = [SLComposeViewController composeViewControllerForServiceType: SLServiceTypeFacebook];
[shareView setTitle:@"Title"];
[shareView setInitialText:@"Description"];
[shareView addURL:[NSURL URLWithString:@"http://www.google.com/"]];
[shareView setCompletionHandler:^(SLComposeViewControllerResult result) {

    switch (result) {
        case SLComposeViewControllerResultCancelled:
        {
            NSLog(@"Facebook Post Canceled");
            break;
        }
        case SLComposeViewControllerResultDone:
        {
            NSLog(@"Facebook Post Successful");
            break;
        }
        default:
            break;
    }
}];

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2.0, [UIScreen mainScreen].bounds.size.height / 2.0);
[activityView startAnimating];
[self.view addSubview:activityView];

[self presentViewController:shareView animated:YES completion:^{
    NSLog(@"Presented facebook");
    [activityView removeFromSuperview];
}];