vendredi 14 août 2015

How Do I Unlock An In-App Purchase Item After It Has Been Purchased?

I have everything setup, and the In-App Purchase items are being saved but when the item is purchased on the MasterViewController and I return to the ViewController, the IAP item is not unlocked in a sense. If I quit the app and reopen it, the IAP item is unlocked. Thats obviously a hassle for users to have to purchase and item, close the app and reopen it for it to be unlocked.

Any help would be greatly appreciated!

Thanks



via Chebli Mohamed

AVPlayerViewController in uicollectionviewcell - cancel touch

i am having a AVPlayerViewControllerin and custom uicollectionviewcell

how can i disable the call to didSelectItemAtIndexPath when touched on the AVPlayer from AVPLayerViewController?

there are a bunch of other elements on the cell, wich should trigger the didSelectItemAtIndexPath

actually on the player controls it works, but once they fade out, another touch on the avplayer triggers the didselect.

having an uibutton in the same cell, cancels the touches correctly.



via Chebli Mohamed

AVQueuePlayer memory issue while looping a playlist in iOS

In my iOS application, I'm trying to play list of videos downloaded to applications' Documents directory. To achieve that target, I used AVQueuePlayer. Following is my code which leads to app crash after 6/7 times looping.

@interface PlayYTVideoViewController () <NSURLConnectionDataDelegate, UITableViewDataSource, UITableViewDelegate> 
{

AVQueuePlayer *avQueuePlayer;

}


- (void)playlistLoop
{
    NSLog(@"%s - %d", __PRETTY_FUNCTION__, __LINE__);

    lastPlayedVideoNumber = 0;

    _loadingVideoLabel.hidden = YES;

    avPlayerItemsMutArray = [[NSMutableArray alloc] init];

    for (NSString *videoPath in clipUrlsMutArr)
    {
        NSURL *vidPathUrl = [NSURL fileURLWithPath:videoPath];

        AVPlayerItem *avpItem = [AVPlayerItem playerItemWithURL:vidPathUrl];

        [avPlayerItemsMutArray addObject:avpItem];
    }

    avPlayerItemsArray = [avPlayerItemsMutArray copy];

    for(AVPlayerItem *item in avPlayerItemsArray)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidPlayToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
    }

    avQueuePlayer = [AVQueuePlayer queuePlayerWithItems:avPlayerItemsArray];

    avQueuePlayer.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;

    introVideoLayer = [AVPlayerLayer playerLayerWithPlayer:avQueuePlayer];

    introVideoLayer.frame = _mpIntroVideoView.bounds;

    [_mpContainerView.layer addSublayer:introVideoLayer];

    [avQueuePlayer play];
}


- (void)itemDidPlayToEndTime:(NSNotification *)notification
{
    NSLog(@"%s - %d", __PRETTY_FUNCTION__, __LINE__);

    AVPlayerItem *endedAVPlayerItem = [notification object];

    [endedAVPlayerItem seekToTime:kCMTimeZero];

    for (AVPlayerItem *item in avPlayerItemsArray)
    {
        if (item == endedAVPlayerItem)
        {
            lastPlayedVideoNumber++;
            break;
        }
    }

    [self reloadVideoClipsTable];

    if ([endedAVPlayerItem isEqual:[avPlayerItemsArray lastObject]])
    {
        [self playlistLoop];
    }
}

After getting memory issue, I tried to make some changes to above code.

I tried to set avQueuePlayer variable public and set it as strong variable

 @property (strong, nonatomic) AVQueuePlayer *avQueuePlayer;

By doing that I expected avQueuePlayer variable remain in the memory till we manually set to nil. But that didn't solve the problem.

Then I tried to set player, related arrays and layers to nil and created again for new loop session.

if (avPlayerItemsMutArray != nil)
    {
        avPlayerItemsMutArray = nil;
    }

avPlayerItemsMutArray = [[NSMutableArray alloc] init];

if (avPlayerItemsArray != nil)
    {
        avPlayerItemsArray = nil;
    }

avPlayerItemsArray = [avPlayerItemsMutArray copy];

if (avQueuePlayer != nil)
    {
        avQueuePlayer = nil;
    }

avQueuePlayer = [AVQueuePlayer queuePlayerWithItems:avPlayerItemsArray];

if(introVideoLayer != nil)
    {
        [introVideoLayer removeFromSuperlayer];
        introVideoLayer = nil;
    }

introVideoLayer = [AVPlayerLayer playerLayerWithPlayer:avQueuePlayer];

But that also didn't help to solve the issue.

Next I try to remove the observer before it re-initialized in a new loop

if (avPlayerItemsArray != nil)
{
    avPlayerItemsArray = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AVPlayerItemDidPlayToEndTimeNotification
                                                  object:nil];
}

But that also didn't help.

Next I used Instrument to find out memory usages and leaks. Application is not exceeding 18 MB when it is crashing and also there were more than 200 MB remaining as free. Instruments is little more complicated but still I didn't find any memory leaks related to this code.



via Chebli Mohamed

MailCore2 Is it possible to check which email email has been replied iphone

I am working on an iphone app which uses MailCore2 to fetch and send emails. Everything is working fine. I want to set a flag which will display that an email has been replied. Is it possible with MailCore2.

Thanks in advance.



via Chebli Mohamed

Framework CFBundleIdentifier Collision

I've made a custom SDK using Cocoa Touch Framework (followed these instructions to make it http://ift.tt/1KQdWFF) .

One app, that is using this SDK is already uploaded to app store and is reviewed by apple and all is well. Now I'm trying to submit second app to App store. All is well on the xCode, it shows that upload was completed successfully, but few minutes after uploading I get a letter that says:

CFBundleIdentifier Collision - The Info.plist CFBundleIdentifier value 'com.company.MySDK' of 'http://ift.tt/1Nd4egN' is already in use by another application.

I don’t understand why apple even checks the app framework's bundleidentifier. Looks like there are lot of similar issues with using different bundles, but I haven not found a fix that would work for this issue.

Would be really thankful for help, thanks!



via Chebli Mohamed

After dismissing imagePickerController memory not being released

I'm calling [picker dismissViewControllerAnimated:YES completion:NULL]; when user either chooses a picture from the library or cancels. I'm also setting delegate to nil just to be sure but that doesn't help either.

Am I missing something?



via Chebli Mohamed

Mirrioing facebook comments in ios

Referring to this URL http://ift.tt/1Cb1f2a , I am searching for possibility of facebook comments mirriong in ios app. After googling, not able to get the proper docs or any links to do it in iOS. Is it possible in ios ? Any help or links will be appreciated. Thanks.



via Chebli Mohamed

Some questions with NetFSMountURLAsync?

I am working on a OS X app which mount server volumes through NetFSMountURLAsync. And now I have many questions.

  • When I successfully mounting a volume from server and I want to check if the share always available. Then I close the share, but I can still check it's online through NSFileManager's mountedVolumeURLsIncludingResourceValuesForKeys: options:. Afterwards I use getResourceValue: forKey: error: to retrieve volumename by NSURLVolumeNameKey so I can get offline status if there is not volume name exists, but it is still not quick enough. How to get status change immediately?

  • When I just mount and unmount a volume repeatly, I found the memory keep increasing even I stop any operations it still keep high memory and not release. I use ARC and no other operations. At the same time, NetAuthSysAgent's memory also keep increasing, Any ideas?

  • And last when it takes long time to mount I use NetFSMountURLCancel to cancel a mount, but sometimes it just hang there and do not terminate. How's that happens?



via Chebli Mohamed

jeudi 13 août 2015

iOS- parse framework nested query

I have two tables TrendingUsers and Follow. Functionality required is like fetch users from TrendingUsers table and offer to follow, provided fetched user is not from user's follow list. If user is already get followed then skip.

Follow table has columns follower and leader.

PFQuery *followTableQuery = [PFQuery queryWithClassName:@"Follow"];
[querySelf whereKey:@"follower" equalTo:[PFUser currentUser] ];
[querySelf whereKey:@"leader" equalTo:@"fetchedUserObject" ];
[querySelf findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        if (objects.count) {
          //if following objects array will have single object
        }
        else
        {
            //not following to @"fetchedUserObject" user
        }

    }
  }
 ];

This will confirm me that currentUser is following @"fetchedUserObject" user or not. Now I want to integrate this to the TrendingUsers table query to fetch only such users that currentUser is not following.



via Chebli Mohamed

C programming Zig Zag pratice

I have a exercise in objective C by using For, If-else, printf to print a Zig-Zag like this in console :

+       +       +

+ + + + + + + + + + + + + + + + + +

I try many way but keeping fail all times. I really need helps. Thank you.



via Chebli Mohamed

Initiating Background transfer service in background fetch ios

My objective is to send data/image to the server when the app is in background. From iOS7, we can do this using background fetch. But the background fetch only offers 30 sec time limit. The data which I am sending to the server may take longer time since it has more images. While googling I came across Background Transfer Service which offers unlimited time to upload/download data in the background. Is it possible to initiate the background transfer service in the background fetch code? If so how to handle it.



via Chebli Mohamed

Check for resource fork in Objective C

How do i check whether a file exists with resource fork or not?

Note : With out using the API's of CarbonCore->Resources.h, Since they are deprecated.



via Chebli Mohamed

UIPaveViewController with page indicator overlaying content

In my app I have a screen that contains UIPageViewController. It takes part of the screen, so I've put it inside the container app.

To show the page controller I do the following

[self addChildViewController:self.pageController];
[self.pageContainerView addSubview:self.pageController.view];

In order to make page controller fit the container view's size, I've added constraints (using Pure Layout library)

- (void)updateViewConstraints {
    [super updateViewConstraints];

    if (!self.didUpdateConstraints) {

        [self.pageContainerView addConstraints:[self.pageController.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero]];

        self.didUpdateConstraints = YES;
    }
}

Everything works fine here, except for 1 thing.

On the content controller (which is displayed inside page controller) I have an image view and 2 labels. Image view takes the whole screen, and labels overlay that image view.

My assumption was that in the page view controller, the image view would also take all the space of the container view and page indicator would be overlaying the image view.

In reality, page indicator is UNDER the image view. This way, the image view does not take the whole container's space, but is narrowed to place page indicator under it.

Is there a way to do it the way I want? I.e. Image view taking all the container's space and page indicator overlaying it.



via Chebli Mohamed

Getting XMPP client chat history between two users

I have created a XMPP Swift Messenger with the eJabbered, but it doesn't save the history.

I searched a lot and could found just answers written in ObjC, in Stack.

For instance:

- (void)loadChatHistoryWithUserName:(NSString *)userName {
    NSString *userJid = [NSString stringWithFormat:@"%@@%@",userName,self.hostName];
    NSManagedObjectContext *moc = [_xmppMsgStorage mainThreadManagedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
                                                     inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
    NSError *error;
    NSString *predicateFrmt = @"bareJidStr == %@";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFrmt, userJid];
request.predicate = predicate;
    NSArray *messages = [moc executeFetchRequest:request error:&error];
}

But I use XMPP Swift Framework with the XMPP ObjC Framework inside. Look at this Git: GitHub

How can I use those snippet in Swift for getting chat history?



via Chebli Mohamed

images not showing in pdf preview?

Strange feeling that if i want to preview a pdf on a controller alongside an image the only way i can get it to work is to use a defined segue from the previous view controller, maybe i'm not clear. How to i get an image to show up on a preview of a QuickLook action without having to segue in and not just modal into the view ? Is this logical ?

I dev an app which generates PDF's, and i'm giving the user the possibility to preview them....but when these have an image....boom the image disappears from the preview...unless i use a segue then no problem, seems weird though. Any suggestions ?....thanks in advance...



via Chebli Mohamed

iOS - MPMoviePlayer is not allowing to pause the video

I am working on MPMoviePlayerController.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileURL = [NSString stringWithFormat:@"%@/FileName.mp4", documentsDirectory];
myMoviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:fileURL]];
myMoviePlayer.backgroundView.backgroundColor = [UIColor blackColor];
[[myMoviePlayer view] setFrame:CGRectMake(0, 0, self.view.frame.size.width, getReadyMoviePlayerView.frame.size.height)];
[myMoviePlayerView addSubview:[myMoviePlayer view]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinished:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:myMoviePlayer];
myMoviePlayer.controlStyle = MPMovieControlStyleEmbedded;
myMoviePlayer.shouldAutoplay = NO;
myMoviePlayer.fullscreen = NO;
myMoviePlayer.repeatMode = MPMovieRepeatModeOne;
[myMoviePlayer prepareToPlay];
[myMoviePlayer play ];


-(void)moviePlayBackDidFinished:(NSNotification *)dict{

    if (dict.object == myMoviePlayer) {

        NSInteger reason = [[dict.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
        if (reason == MPMovieFinishReasonPlaybackEnded){

            [myMoviePlayer prepareToPlay];
            [myMoviePlayer play];
        }
    }
}

Now the problem is that, The play and pause button is not working. I am not able to pause the video by using MPMoviePlayer Controls.

This problem is with both OS that is iOS 7 and iOS 8 also.

Is there any solution to pause the running video.

Thank you



via Chebli Mohamed

Facebook Custom login UI with sdk 4

Im using this code for custom login ui from Facebook developer page, It gave me a log message "FBSDKLog: starting with Graph API v2.4, GET requests for /me should contain an explicit "fields" parameter". Kindly tell me how can i remove this

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logInWithReadPermissions:@[@"public_profile"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { NSLog(@"%@", result); if (error) {

    }
    else if (result.isCancelled)
    {
    }
    else
    {
       if ([result.grantedPermissions containsObject:@"email"])
        {

        }
    }
}];



via Chebli Mohamed

Image Animation not working

I want to animated image after 0.7 sec but they not working they do not show image on my View.

NSMutableArray *images = [[NSMutableArray alloc] init];
[images addObject:[UIImage imageNamed:@"L1.png"]];
[images addObject:[UIImage imageNamed:@"L2.png"]];
[images addObject:[UIImage imageNamed:@"L3.png"]];
[images addObject:[UIImage imageNamed:@"L4.png"]];
[images addObject:[UIImage imageNamed:@"L5.png"]];
[images addObject:[UIImage imageNamed:@"L6.png"]];
[images addObject:[UIImage imageNamed:@"L7.png"]];
[images addObject:[UIImage imageNamed:@"L8.png"]];
[images addObject:[UIImage imageNamed:@"L9.png"]];
[images addObject:[UIImage imageNamed:@"L10.png"]];
[images addObject:[UIImage imageNamed:@"L11.png"]];
[images addObject:[UIImage imageNamed:@"L12.png"]];
self.imagsd.animationImages=images;
self.imagsd.animationDuration=0.7;



via Chebli Mohamed

How to change the default image of facebook button in ios

Please Help

This is what happening now...custom image what i need is overlapping with the log-in text of default facebook button ,but i don't want default log-in text which is in background.it is also automatically logging-in.. once if i log in in the app



via Chebli Mohamed

Can I still use bridging header for cocoa pod frameworks?

I used to download Parse frameworks and bridge to my Swift project using bridging header file with this line:

#import <Parse/Parse.h>

Now I just switched to use cocoa pods and things get messed up when I include use_frameworks! in the Podfile. Keeping the bridging file the same, all of the PFObjects become unresolved identifier when build. This error goes away when I put

import Parse

at the top of each file. But that is pretty much every file since it is a Parse project, let alone other things to import such as ParseUI etc. Is there a way to import once for all as the bridging header used to do?

I tried to change the import line in the bridging header to:

import "Parse.h"

It gives me another error saying "duplicate interface definition for class 'Parse'":

MyApp/Pods/Parse/Parse/Parse.h:66:1: error: duplicate interface definition for class 'Parse'
@interface Parse : NSObject
^
/Library/Developer/Xcode/DerivedData/MyApp-dbdwtdjelpuomaaawugvjubngrvq/Build/Products/Debug-iphonesimulator/Parse.framework/Headers/Parse.h:66:12: note: previous definition is here
@interface Parse : NSObject
           ^

I checked other questions here but got no luck. Any help?



via Chebli Mohamed

how can solve app is background mode that time not get quickbox videocall in ios?

I have try set background mode likeenter image description here

Status bar in seeing red color but not get any video call.

So please help me how to solve my issue.



via Chebli Mohamed

UITextField becomeFirstResponder does not work in UIControlEventEditingDidEndOnExit

I have a UITextField and UILabel. When user entered some text to textField and tap "Enter" on keyboard I want to save text to the label then clear textField and make it first responder again. But something is going wrong. becomeFirstResponder does not work.

Here is the code of ViewController:

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.textField addTarget:self action:@selector(saveResult:) 
        forControlEvents:UIControlEventEditingDidEndOnExit];
}

-(void) saveResult: (id) sender {
    self.label.text = self.textField.text;
    self.textField.text = @"";
    [self.textField becomeFirstResponder];
}

@end



via Chebli Mohamed

How to get venues which are near to me

For fetching all venues around me, I use Foursquare API 2 with the following code:

[Foursquare2 venueSearchNearByLatitude: @(...0)
                             longitude: @(...0)
                                 query: nil
                                 limit: nil
                                intent: intentCheckin
                                radius: @15000
                            categoryId: nil
                              callback: ^(BOOL success, id result)

It works. I get 50 venues with distance from 0 to 300 meters. If I put parameter 'query' like @"garden", then I get 50 different venues in which I see venue "garden" with distance 30 meters but I don't see one in the first list. Why? How can I get venue 'garden' without query? I tried intent as 'intentBrowse'. But in this case, I can see my "garden" if I put radius as 100 meters. If more, I see venues with distances from farther to nearest and my 'garden' misses that list because it is too near to me. So my question is: How I can get the real list of places around me? If it's possible.



via Chebli Mohamed

Unable to identify the cause of unrecognized selector error

So I'm building this iOS app. Everytime the use taps on a small square that square should change color. I've made sure that all my methods are defined. And I've changed the name of the xIndex value so that I can ENSURE that it isn't the view's .xIndex value that's the source of the crash. But no matter what I seem to do, I still seem to get:

'-[UIView xIndex]: unrecognized selector sent to instance 0x7fe06be6ce70'

Note that the above instance refers to the memory address of specificSquare. Any guesses? Been battling this for hours.

- (void)handleFunViewSquareTap:(UITapGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // handling code
        CGPoint locationOfTap = [sender locationInView: self.view];
        NSInteger xVIndex = floorf(locationOfTap.x / 40.f);
        NSInteger yIndex = floorf(locationOfTap.y / 40.f);

        // find the view that matches these indexes
        for(FunViewSquare *specificSquare in [self.view subviews])
        {
            if((specificSquare.xIndex == xVIndex) && (specificSquare.yIndex == yIndex))
           {
//                //specificSquare.backgroundColor = [ViewController randomColor];
           }
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

        CGRect frameRect = self.view.frame;
        NSInteger xIndex, yIndex = 0;
        for( CGFloat yPosition = 0.0; yPosition < frameRect.size.height; yPosition+=40.0f )
        {
            // reset xIndex on every iteration
            xIndex = 0;
            for( CGFloat xPosition = 0.0; xPosition < frameRect.size.width; xPosition+=40.0f )
            {
                FunViewSquare *randomSquare = [[FunViewSquare alloc] initWithFrame: CGRectMake(xPosition, yPosition, 40.f, 40.0f)];

                if(randomSquare)
                {
                    randomSquare.backgroundColor = [ViewController randomColor];
                    randomSquare.xIndex = xIndex;
                    randomSquare.yIndex = yIndex;
                    [self.view addSubview: randomSquare];
                }
                xIndex++;
            }
            yIndex++;
        }

        butGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleFunViewSquareTap:)];
        if(butGestureRecognizer)
        {
            [self.view addGestureRecognizer: butGestureRecognizer];
        }

}


+ (UIColor *)randomColor
{
    UIColor *colorToReturn;

    uint32_t randomNumber = random();
    randomNumber = (randomNumber % 10); // a random number between 0 & 10

    switch(randomNumber)
    {
        case 0 :
            colorToReturn = [UIColor blueColor];
            break;
        case 1 :
            colorToReturn = [UIColor grayColor];
            break;
        case 2 :
            colorToReturn = [UIColor greenColor];
            break;
        case 3 :
            colorToReturn = [UIColor purpleColor];
            break;
        case 4 :
            colorToReturn = [UIColor redColor];
            break;
        case 5 :
            colorToReturn = [UIColor brownColor];
            break;
        case 6 :
            colorToReturn = [UIColor cyanColor];
            break;
        case 7 :
            colorToReturn = [UIColor orangeColor];
            break;
        case 8 :
            colorToReturn = [UIColor magentaColor];
            break;
        case 9 :
            colorToReturn = [UIColor whiteColor];
            break;
        default :
            colorToReturn = [UIColor blackColor];

    }
    return(colorToReturn);
}

@end



via Chebli Mohamed

How to get data(string,url,image,etc) from UIPasteboard while App is in Background State


i was digging on "How to get data from UIPasteboard while App is in background state" but could not find something useful.
i followed this Link and this but not helpful. any suggestions will be appreciated.



via Chebli Mohamed

How can I reload a created NSBundle again after its dynamically updated?

I have a scenario in which I have localization files to be downloaded from server. I download the file at start of application and store it in folder in bundle. Like if its English file I store it in bundle under folder 'en.lproj' with name Localizable.strings.

Now when file is downloaded, I load the bundle using bundleWithPath: method. Once it is loaded I show localization using method

NSLocalizedStringFromTableInBundle(key, @"Localizable", bundle, @"");

Till here it works fine. Now if the file is updated from server I again download the English file and I replace the old file with new one. But the application shows the localization from old file which was replaced. Can anyone please tell me if we can reload the bundle again so that the updates are reflected.

In the above scenario the application is not killed when file is updated. If I kill the application and restart it then the changes are reflected. But I want the changes to be reflected without killing the application.



via Chebli Mohamed

Unicode character issue while reading from csv file

In my program, i read the content from csv file then display in UILabel.

What is my problem is Unicode character not working while read it from file.

Suppose i do the code like this.

NSString *cubedSymbol = @"10\u00B3";

[label setText:cubedSymbol ];

Output 10³

But same text @"10\u00B3" i read from the file and set it to label.

output 10\u00B3



via Chebli Mohamed

IOS - Parse.com - Current User nil after kill app on ios 7

I coding a ios app with parse SDK on IOS. i check user logged in by

[PFUser currentUser] != nil

I check it when the app is killed by user, and open again. It worked fine on ios 8. But when i check on ios 7.1, currentUser is nil. Look like it logged out automatic or currentUser did not save.

Oh, I using parse SDK 1.7.5. A new version is 1.8.0, maybe i should update it?

Sorry for my bad english.



via Chebli Mohamed

UIView Animation with Simultaneous Counting Thread

I am trying to get a UIView to expand using an animation block, which works perfectly. However, I want a UILabel to start at 0 and every 0.01 seconds to add 1 till it gets to 100. I created a thread after the animation to accomplish this and it works but it causes the animation I setup to do nothing. I have tried many different things but have had no luck. What would be the best way to accomplish this?

My simplest attempt with the same result as all the others:

[UIView animateWithDuration:1 animations:^{
    _lView.frame = CGRectMake(_lView.frame.origin.x,_lView.frame.origin.y+_lView.frame.size.height,_lView.frame.size.width,-500);
}];

[[[NSThread alloc]initWithTarget:self selector:@selector(startcounting) object:nil]start];


-(void)startcounting{
for(int x=0; x<100; x++){
    [NSThread sleepForTimeInterval:0.01];
    ++_mcount;
    dispatch_async(dispatch_get_main_queue(), ^{
        _cLabel.text = [NSString stringWithFormat:@"%i",_mcount];
    });
  }
}



via Chebli Mohamed

Adding Enemies While Paused

When I pause the game and wait some time, then resume the game, an alien ship is immediately added. How do I make it so that the 'timer' doesn't continue once the game is paused?

My Code:

@implementation GamePlayScene
-(void) didMoveToView:(SKView *)view {
               ...
    self.addAlienTimeInterval = [Util randomWithMin:10 max:25];
    self.timeSinceLastAlien = 0;
               ...
}
-(void) update:(NSTimeInterval)currentTime{
    if (!_isGamePaused){
        if (self.lastUpdateTimeInterval){
            self.timeSinceLastAlien += currentTime - self.lastUpdateTimeInterval;
        }
        if (self.timeSinceLastAlien > self.addAlienTimeInterval && !self.gameOver){
            [self addAlienShip];
            self.timeSinceLastAlien = 0;
        }
        self.lastUpdateTimeInterval = currentTime;
                ...
}
@end



via Chebli Mohamed

How to update the color of section title without uitableview reloadData

I'm using willDisplayHeaderView to change the color of section title:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.textLabel.textColor = [UIColor grayColor];
}

Now, I want to update the color of a section title, how to do it without [tableview reloadData]?



via Chebli Mohamed

Xcode obj - C: I can't retrieve variable from another class's instance variable

In my WhatToEditViewController, I created an NSString property called whattoedit. When the user presses a certain button, whattoedit gets assigned to a string.

@interface WhatToEditViewController : UIViewController

@property (nonatomic, strong) NSString * whattoedit;

@end

#import "WhatToEditViewController.h"

implementation:

@implementation WhatToEditViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)TappedMorning:(id)sender {
self.whattoedit = @"Morning";

}
- (IBAction)TappedAfternoon:(id)sender {

self.whattoedit = @"Afternoon";
}
- (IBAction)TappedEvening:(id)sender {

self.whattoedit = @"Evening";

}

(I checked this part of my program works :/) Also when the user presses the button, a new view controller called SettingsTableViewController gets pushed in. What I want to do is set the title of the navigation bar of SettingsTableViewController as WhatToEditViewController's whattoedit property.

Here is SettingsTableViewController's implementation:

#import "SettingsTableViewController.h"
#import "WhatToEditViewController.h"

@interface SettingsTableViewController ()

@end

@implementation SettingsTableViewController



- (void)viewDidLoad {
[super viewDidLoad];

WhatToEditViewController * editMode = [[WhatToEditViewController alloc] init];

self.navigationController.navigationBar.topItem.title = editMode.whattoedit;

Oddly, the navigation bar title turns into (null). Should the navigationBar.title code be in the viewdidload?

Thanks, Fez



via Chebli Mohamed

Building An RTP Server in iOS That Allows WiFi Speakers To Stream Music

A Little Background On Why I Have To Do This

I am currently optimising an app in order to improve the transferring of media files to the WiFi speakers that our team developed. Our solution before was using iPhone as an HTTP server and then allow the speakers to connect and download music from it. But unfortunately a lot of problems occurred such as frequent slow transfer speed, file read failure, and when user uses the "seek" command, the speakers would have to download the whole file in order for it to seek into that particular time before it starts to play. This is a very bad experience for our users.

What I Need

In order to solve the problem I mentioned above. We thought of changing the HTTP server to an RTP server that will be ran on an iPhone and then allows the WiFi speakers to stream music from it. However, from what I read on other Q&A platforms they mentioned that iPhone does that support transferring of data using RTP. I also tried searching here in stack but were not able to find an answer that solves my problem.

My Question

Is it possible to run an RTP server on iPhone and is there any demo about this that I can refer to?

Any suggestions would be high appreciated.



via Chebli Mohamed

Parse local data store in Dating App like badoo. Urgent

Hello, iam develooing an Dating App like baddo with Parse and i want to store data to be accesible offline (Users find near you, Messages list e Conversations) 1. How to activate in AppDelegate and in ViewsControllers? 2. Give me and simple exemple with my own code if possible. Thanks

Messages list viewController

PFQuery *messageQueryFrom = [MessageParse query];
[messageQueryFrom whereKey:@"fromUserParse" equalTo:[UserParseHelper currentUser]];
PFQuery *messageQueryTo = [MessageParse query];
[messageQueryTo whereKey:@"toUserParse" equalTo:[UserParseHelper currentUser]];
PFQuery *both = [PFQuery orQueryWithSubqueries:@[messageQueryFrom, messageQueryTo]];
[both orderByDescending:@"createdAt"];

[both findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)

Conversation Viewcontroller

 (void)getMessages

PFQuery *query1 = [MessageParse query];
[query1 whereKey:@"fromUserParse" equalTo:[PFUser currentUser]];
[query1 whereKey:@"toUserParse" equalTo:self.toUserParse];
[query1 whereKey:@"text" notEqualTo:@""];


PFQuery *query2 = [MessageParse query];
[query2 whereKey:@"fromUserParse" equalTo:self.toUserParse];
[query2 whereKey:@"toUserParse" equalTo:[PFUser currentUser]];
[query2 whereKey:@"text" notEqualTo:@""];




PFQuery *orQUery = [PFQuery orQueryWithSubqueries:@[query1, query2]];
[orQUery orderByAscending:@"createdAt"];





[orQUery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    self.messages = [objects mutableCopy];
    [self.collectionView reloadData];
    [self scrollCollectionView];
    for (MessageParse *message in objects) {
        message.read = YES;
        [message saveInBackground];
    }
}];

User near viewcontroller

(void)queryParseMethod {NSLog(@"start query");

PFQuery *query = [UserParseHelper query];
[query whereKey:@"username" notEqualTo:self.mainUser.username];
PFGeoPoint *userGeoPoint = self.mainUser.geoPoint;

[query whereKey:@"geoPoint" nearGeoPoint:userGeoPoint];

if (self.segmentedControl.selectedSegmentIndex == 0) {
    [query whereKey:@"isMale" equalTo:@"true"];

}
if (self.segmentedControl.selectedSegmentIndex== 1) {
   [query whereKey:@"isMale" equalTo:@"false"];

}


PFUser *chekUser = [PFUser currentUser];
NSString *vip = chekUser[@"membervip"];
if ([vip isEqualToString:@"vip"]) {

    NSLog(@"Unlim - vip member");
    self.upgradeVip.hidden = YES;

} else{

    NSLog(@"No Unlim - no vip member");
 //   query.limit = limitQueruNoVipUser;
    self.upgradeVip.hidden = NO;

}

[query whereKey:@"geoPoint" nearGeoPoint:self.mainUser.geoPoint withinKilometers:self.mainUser.distance.doubleValue];



[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        imageFilesArray = [[NSArray alloc] initWithArray:objects];


       [_imagesCollection reloadData];
        [_imagesCollection performBatchUpdates:nil completion:nil];
    }
}];

}



via Chebli Mohamed

Admob not archiving in Xcode but working on iphone 5 and simulator

For some reason Xcode is not archiving my project after adding AdMob to it.

I am currently using -objc and -all_load in the project because I am using Adobe Creative. Its working perfectly on an iPhone 5 and simulator but when I want to archive the project to upload it to the store it gave me duplicate symbols everywhere and it started after adding Admob.

Ld /Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/IntermediateBuildFilesPath/MemeHub.build/Release-iphoneos/MemeHub.build/Objects-normal/arm64/MemeHub normal arm64
    cd /Users/Jose/memehub
    export IPHONEOS_DEPLOYMENT_TARGET=7.0
    export PATH="/Applications/http://ift.tt/1eHCv98"
    /Applications/http://ift.tt/1jmLxI7 -arch arm64 -isysroot /Applications/http://ift.tt/1I4Nh3L -L/Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/BuildProductsPath/Release-iphoneos -F/Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/BuildProductsPath/Release-iphoneos -F/Users/Jose/memehub/MemeHub -F/Users/Jose/memehub/AdobeCreativeSDKFrameworks -F/Users/Jose/Documents/FacebookSDK -F/Users/Jose/memehub/MemeHub/Chartboost -F/Users/Jose/memehub -filelist /Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/IntermediateBuildFilesPath/MemeHub.build/Release-iphoneos/MemeHub.build/Objects-normal/arm64/MemeHub.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -dead_strip -ObjC -all_load -fobjc-arc -fobjc-link-runtime -miphoneos-version-min=7.0 -framework UIKit -framework StoreKit -framework QuartzCore -framework OpenGLES -framework MessageUI -framework Foundation -lz.1.2.5 -lsqlite3.0 -framework CoreData -framework Accelerate -framework MobileCoreServices -framework GoogleMobileAds -framework AdobeCreativeSDKFoundation -lc++ -framework Social -framework Accounts -lsqlite3 -lz -framework SystemConfiguration -framework Security -framework FBSDKMessengerShareKit -framework CoreLocation -framework CoreGraphics -framework CFNetwork -framework Chartboost -framework AudioToolbox -framework Parse -framework ParseUI -framework AdobeCreativeSDKImage -framework Bolts -Xlinker -dependency_info -Xlinker /Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/IntermediateBuildFilesPath/MemeHub.build/Release-iphoneos/MemeHub.build/Objects-normal/arm64/MemeHub_dependency_info.dat -o /Users/Jose/Library/Developer/Xcode/DerivedData/MemeHub-eiiudjckcbcbreabjhqaziopvmmq/Build/Intermediates/ArchiveIntermediates/MemeHub/IntermediateBuildFilesPath/MemeHub.build/Release-iphoneos/MemeHub.build/Objects-normal/arm64/MemeHub

>duplicate symbol l016 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdAppViewController.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADBannerAdViewDelegate.o)
duplicate symbol l016 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdAppViewController.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdImage.o)
duplicate symbol l021 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
duplicate symbol l022 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
duplicate symbol l023 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
duplicate symbol l024 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
duplicate symbol l026 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMAdManager.o)
duplicate symbol l005 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMWebViewRenderedChecker.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdViewRenderedChecker.o)
duplicate symbol l006 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMWebViewRenderedChecker.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdViewRenderedChecker.o)
duplicate symbol l012 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADCSIReporter.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADPinger.o)
duplicate symbol l023 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADCSIConfiguration.o)
duplicate symbol l022 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l023 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l024 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l025 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l026 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l027 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l028 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l029 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l030 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l031 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l032 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l033 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdSize.o)
duplicate symbol l025 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTransparentOverlayPresenter.o)
duplicate symbol l026 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTransparentOverlayPresenter.o)
duplicate symbol l027 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADLocation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTransparentOverlayPresenter.o)
duplicate symbol l028 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTransparentOverlayPresenter.o)
duplicate symbol l029 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTokenDispenser.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADTransparentOverlayPresenter.o)
duplicate symbol l016 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdAppViewController.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdNetworkJavaScriptAdViewDelegate.o)
duplicate symbol l017 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADRewardBasedVideoAd+Mediation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADAdNetworkJavaScriptAdViewDelegate.o)
duplicate symbol l018 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADRewardBasedVideoAd+Mediation.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMRAIDPicture.o)
duplicate symbol l021 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMRAIDResizeProperties.o)
duplicate symbol l022 in:
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADNativeAdAttribution.o)
    /Users/Jose/memehub/GoogleMobileAds.framework/GoogleMobileAds(GADMRAIDResizeProperties.o)
ld: 33 duplicate symbols for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)



via Chebli Mohamed

NSAppKitVersionNumber10_10 doesn't work

I am using below code to check OS X version at runtime.

if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10)
{
    /* On a 10.10.x or earlier system */
}

But this condition return false on 10.10.4 OS X. I am using Xcode 6.3.2.

enter image description here

According to AppKit Release Notes for OS X v10.11, It should work.

if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) {
  /* On a 10.9.x or earlier system */
} else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10) {
  /* On a 10.10 - 10.10.x system */
} else {
  /* 10.11 or later system */
}



via Chebli Mohamed

- (void)scrollViewDidScroll:(UIScrollView *)scrollView too slow in iOS 8

I have a problem where scrolling up/down and setting the contentoffset from within scrollviewdidscroll on a secondary scrollview causes a minor jittery behaviour... or more accurately a low frame rate.

I currently rely on scrollViewDidScroll to manage effects such as Parallax in my UIScrollView, these effects are applied by listening for scrollViewDidScroll, but the turn around time for each call of this method is (for some reason), too slow and causes enough of a delay for it to look kind of bad when scrolling.

Interestingly, iOS 9, runs fine.

I've tried alternative methods, such as turning off images or using AsyncDisplayKit but both have no effect on the number of times scrollViewDidScroll is fired.

It looks to me that I may need to rearchitect the way I create the parallax effect, but I'm hesitant to in case there is a quick fix.



via Chebli Mohamed

Google Drive API IOS

First, I have implemented a GTMOAuth that asks the user for KGTLAuthScopeDriveMetadata. That functions correctly.

So I am able to get a list of files by providing a folder id following this code: http://ift.tt/1zCF6rB

- (void)loadDriveFiles {
  GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
  query.q = @"mimeType = 'text/plain'";

  UIAlertView *alert =
      [DrEditUtilities showLoadingMessageWithTitle:@"Loading files"
                                          delegate:self];
  [self.driveService executeQuery:query
                completionHandler:^(GTLServiceTicket *ticket,
                                    GTLDriveFileList *files,
                                    NSError *error) {
      [alert dismissWithClickedButtonIndex:0 animated:YES];
      if (!error) {
        self.driveFiles = [files.items mutableCopy];
        [self.tableView reloadData];
      } else {
        NSLog(@"An error occurred: %@", error);
        [DrEditUtilities showErrorMessageWithTitle:@"Unable to load files"
                                           message:[error description]
                                          delegate:self];
      }
  }];
}

So now when I try to download one of those files, none of the gtldrivefiles have the property downloadurl. They do have webcontentlink, alternateurl. Thus I cannot download the file. I have followed this code: http://ift.tt/Q3fmNw to download a file, but as can be seen the property downloadurl is needed.

note that the types of files that do not have a downloadurl property is mp4, mov, jpg, etc.

any reason as to why i never get the downloadurl property?

Note: I do ask the user on login for full access to the drive.



via Chebli Mohamed

iOS table view in modal gets shorter every time view appears

Here's my set up: I have a tab bar controller as my root view controller. In one tab, I present a modal on user action. The modal has a navigation controller, and view controller with a table view as it's root view controller. On another user action, I push another view controller. Every time I pop back to the table view, the content size seems to have shrunk. The table view gets shorter and shorter in appearance. This does not correlate to change in size of the table view. When I log i always get back the same tableView size and content size, but the content is getting eaten from below.



via Chebli Mohamed

Maintaining the pause screen while minimizing app

I'm trying to make it so that when I minimize my app the pause screen is displayed and when I return to it, it is still maintained; you would have to tap the resume button to continue playing. I have managed to make it so that the game is paused when the app is minimized but the 'paused state' is not displayed. Also, when i press the pause button, minimize the app and then come back to it, it displays the 'Paused' text and has the resume button, but it resumes the game anyways. How would I fix this issue? It's been bothering me for a while. My Code:

AppDelegate.m
- (SKView*)getSKViewSubview{
    for (UIView* s in self.window.rootViewController.view.subviews) {
        if ([s isKindOfClass:[SKView class]]) {
            return (SKView*)s;
        }
    }
    return nil;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    SKView *view = [self getSKViewSubview];
    if (view){
        view.paused = YES;
    }
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    SKView* view = [self getSKViewSubview];
    if (view) {
        view.paused = YES;
    }
}

GamePlayScene.m
-(void)update:(NSTimeInterval)currentTime{
          ...
 if (self.view.paused == YES){
        for (SKSpriteNode *node in [self children]){
            if ([node.name isEqualToString:@"PauseButton"]){
                [node removeFromParent];
                [self resumeButton];
            }
        }
    }
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
                      ...
        if ([node.name isEqualToString:@"PauseButton"]){
            [self runAction:self.buttonSFX];
            [self performSelector:@selector(pauseGame) withObject:nil afterDelay:1/60.0];
            [node removeFromParent];
            [self resumeButton];
            self.pausedLabel.hidden = NO;
        }
        if ([node.name isEqualToString:@"ResumeButton"]){
            [self runAction:self.buttonSFX];
            self.paused = NO;
            [node removeFromParent];
            [self pauseButton];
            self.pausedLabel.hidden = YES;
            [[GameState sharedInstance] saveState];
        }
                      ...
}



via Chebli Mohamed

GPUImage shader crashing with "ERROR: One or more attached shaders not successfully compiled"

I'm trying to build a Vibrance filter for GPUImage based on this Javascript:

/**
 * @filter       Vibrance
 * @description  Modifies the saturation of desaturated colors, leaving saturated colors unmodified.
 * @param amount -1 to 1 (-1 is minimum vibrance, 0 is no change, and 1 is maximum vibrance)
 */
function vibrance(amount) {
    gl.vibrance = gl.vibrance || new Shader(null, '\
        uniform sampler2D texture;\
        uniform float amount;\
        varying vec2 texCoord;\
        void main() {\
            vec4 color = texture2D(texture, texCoord);\
            float average = (color.r + color.g + color.b) / 3.0;\
            float mx = max(color.r, max(color.g, color.b));\
            float amt = (mx - average) * (-amount * 3.0);\
            color.rgb = mix(color.rgb, vec3(mx), amt);\
            gl_FragColor = color;\
        }\
    ');

    simpleShader.call(this, gl.vibrance, {
        amount: clamp(-1, amount, 1)
    });

    return this;
}

One would think I should be able to more/less copy paste the shader block:

GPUImageVibranceFilter.h

@interface GPUImageVibranceFilter : GPUImageFilter
{
    GLint vibranceUniform;
}

// Modifies the saturation of desaturated colors, leaving saturated colors unmodified.
// Value -1 to 1 (-1 is minimum vibrance, 0 is no change, and 1 is maximum vibrance)
@property (readwrite, nonatomic) CGFloat vibrance;

@end

GPUImageVibranceFilter.m

#import "GPUImageVibranceFilter.h"

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
NSString *const kGPUImageVibranceFragmentShaderString = SHADER_STRING
(
    uniform sampler2D inputImageTexture;
    uniform float vibrance;
    varying highp vec2 textureCoordinate;
    void main() {
        vec4 color = texture2D(inputImageTexture, textureCoordinate);
        float average = (color.r + color.g + color.b) / 3.0;
        float mx = max(color.r, max(color.g, color.b));
        float amt = (mx - average) * (-vibrance * 3.0);
        color.rgb = mix(color.rgb, vec3(mx), amt);
        gl_FragColor = color;
    }
);
#else
NSString *const kGPUImageVibranceFragmentShaderString = SHADER_STRING
(
    uniform sampler2D inputImageTexture;
    uniform float vibrance;
    varying vec2 textureCoordinate;
    void main() {
        vec4 color = texture2D(texture, textureCoordinate);
        float average = (color.r + color.g + color.b) / 3.0;
        float mx = max(color.r, max(color.g, color.b));
        float amt = (mx - average) * (-vibrance * 3.0);
        color.rgb = mix(color.rgb, vec3(mx), amt);
        gl_FragColor = color;
    }
);
#endif

@implementation GPUImageVibranceFilter

@synthesize vibrance = _vibrance;

#pragma mark -
#pragma mark Initialization and teardown

- (id)init;
{
    if (!(self = [super initWithFragmentShaderFromString:kGPUImageVibranceFragmentShaderString]))
    {
        return nil;
    }

    vibranceUniform = [filterProgram uniformIndex:@"vibrance"];
    self.vibrance = 0.0;

    return self;
}

#pragma mark -
#pragma mark Accessors

- (void)setVibrance:(CGFloat)vibrance;
{
    _vibrance = vibrance;

    [self setFloat:_vibrance forUniform:vibranceUniform program:filterProgram];
}

@end

But that doesn't compile, crashing with:

Failed to compile fragment shader
Program link log: ERROR: One or more attached shaders not successfully compiled
Fragment shader compile log: (null)
Vertex shader compile log: (null)

The error is certainly clear, but being inexperienced with OpenGL ES shaders, I have no idea what the problem actually is.



via Chebli Mohamed

CABasicAnimation responsiveness

I have a custom UIActivityIndicatorView. It is a view, with a CAAnimation on its layer. The problem is the following:

I do some heavy work and create a lot of views. It takes approximately 0.5 seconds. In order for it to be smooth I decided to use activity indicator, while it "happens". It was all fine with default activity indicator, however with the one that I wrote I get unexpected results.

So, when the view loads I launch my activity indicator, which starts animating. When heavy duty work starts my view freezes for 0.5 seconds and when it's done I stop animating it and it disappears. This "freeze" looks very unpleasant to an eye. Because the idea was to keep animating while other views get initialized and added as subviews(although hidden).

I suspect that the problem is that my "activity indicator" is not asynchronous or simply was not coded right.

Here is the code for it:

class CustomActivityIndicatorView: UIView {

// MARK - Variables

var colors = [UIColor.greenColor(),UIColor.grayColor(),UIColor.blueColor(),UIColor.redColor()]

var colorIndex = 0

var animation: CABasicAnimation!

lazy var customView : UIView! = {
    let frame : CGRect = CGRectMake(0.0, 0.0, 100, 100)
    let view = UIView(frame: frame)
    image.frame = frame
    image.center = view.center
    view.backgroundColor = UIColor.greenColor()
    view.clipsToBounds = true
    view.layer.cornerRadius = frame.width/2
    return view
}()

var isAnimating : Bool = false
var hidesWhenStopped : Bool = true

var from: NSNumber = 1.0
var to: NSNumber = 0.0

var growing = false

override func animationDidStart(anim: CAAnimation!) {
}

override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
    growing = !growing

    if growing {
        colorIndex++
        if colorIndex == colors.count {
            colorIndex = 0
        }
        println(colorIndex)
        customView.backgroundColor = colors[colorIndex]
        from = 0.0
        to = 1.0
    } else {
        from = 1.0
        to = 0.0
    }

    if isAnimating {
        addPulsing()
        resume()
    }
}

// MARK - Init

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.addSubview(customView)

    addPulsing()
    pause()
    self.hidden = true
}

// MARK - Func

func addPulsing() {
    let pulsing : CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")

    pulsing.duration = 0.4
    pulsing.removedOnCompletion = false
    pulsing.fillMode = kCAFillModeForwards
    pulsing.fromValue = from
    pulsing.toValue = to
    pulsing.delegate = self

    let layer = customView.layer

    layer.addAnimation(pulsing, forKey: "pulsing")
}

func pause() {
    let layer = customView.layer

    let pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)

    layer.speed = 0.0
    layer.timeOffset = pausedTime

    isAnimating = false
}

func resume() {
    let layer = customView.layer

    let pausedTime : CFTimeInterval = layer.timeOffset

    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0

    let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
    layer.beginTime = timeSincePause

    isAnimating = true
}

func startAnimating () {

    if isAnimating {
        return
    }

    if hidesWhenStopped {
        self.hidden = false
    }
    resume()
}

func stopAnimating () {
    let layer = customView.layer

    if hidesWhenStopped {
        self.hidden = true
    }
    pause()
    layer.removeAllAnimations()
}

deinit {
    println("Spinner Deinitied")
}
}

regarding animationDidStop method:

The idea is the following the view pulsates, and after it has shrunk it starts growing again and the background color is changed.

Any idea on what I'm doing wrong ?

Thank You.



via Chebli Mohamed

iOS-Charts - Make a bar chart and field remaning with other color

I am trying to make a chart exactly as the guide lines of the designer but i am difficulty's in 3 of the things.

This is the guide lines:

Chart made by the designer

And this is what i have done:

Chart that i have made

As you can see it was supposed that the red bar had between self and the target a blue bar. Already try to create a second bar to see if stays behind but that did not work. This is what I tryed

BarChartDataSet *set2 = [[BarChartDataSet alloc] initWithYVals:yVals label:@""];

And then filed with blue bars with heigh of target. But din't work so i have remove that.

Other problem is the left axis labels it starts in zero, and did find way to work around.

The third and last problem is that the T for target stays over the line when the expected was to be after the line.

This is the code that used to obtain the chart:

/*
 *  Method to render the graphic of a given KPI
 *
 *  @param  chartView   BarChartView object type
 *  @param  array   NSMutableArray with array of dictionaries
 *  @param  target  double with target value
 *  @param  granularity NSString ("Monthly", "weekly" or "daily")
 *
 *  @return id  BarCartView
 */
- (id)graphicRenderIn:(BarChartView*)chartView
            withData:(NSMutableArray*)array
              target:(double) target
      andGranularity:(NSString*)granularity{

    _chartView = chartView;
    [_chartView setUserInteractionEnabled:NO];

    // chartView setup
    _chartView.delegate = self;
    _chartView.descriptionText = @"";
    _chartView.noDataTextDescription = @"You need to provide data for the chart.";
    _chartView.maxVisibleValueCount = 60;
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawBarShadowEnabled = NO;
    _chartView.drawGridBackgroundEnabled = NO;
    _chartView.backgroundColor = [UIColor green_title];

    // Ox axis setup
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.spaceBetweenLabels = 0.0;
    xAxis.drawGridLinesEnabled = NO;
    xAxis.axisLineColor = [UIColor turqoise];
    xAxis.labelTextColor = [UIColor white_100];
    xAxis.labelFont = [UIFont Caption1];

    _chartView.leftAxis.drawGridLinesEnabled = NO;
    _chartView.rightAxis.drawGridLinesEnabled = NO;
    _chartView.rightAxis.enabled = NO;

    _chartView.legend.enabled = NO;

    // Oy axis setup
    ChartYAxis *leftAxis = _chartView.leftAxis;
    leftAxis.labelFont = [UIFont Caption1];
    leftAxis.labelTextColor = [UIColor white_100];
    leftAxis.labelCount = 3;
    leftAxis.labelPosition = YAxisLabelPositionInsideChart;
    leftAxis.spaceTop = 0.15;
    leftAxis.axisLineColor = [UIColor turqoise];

    // define TARGET line in graphic
    [leftAxis removeAllLimitLines];
    [self updateTargetLine:target];
    [leftAxis addLimitLine:_line];


    // set data values
    [self setDataCount:array target:target andGranularity:granularity];
    [_chartView animateWithYAxisDuration:2.5];
    return self;
}


/*
 *  Method to setup the horizontal target line
 *
 *  @param  target  double with target value
 *
 *  @return void
 */
- (void) updateTargetLine:(double) target
{
    // single target line
    if (_line == nil)
    {
        ChartLimitLine *targetLine = [[ChartLimitLine alloc] initWithLimit:target label:@""];
        _line = targetLine;
    }

    // target line setup
    if (target != 0 )
    {
        _line.label = @"T";
    }
    _line.lineWidth = 0.8;
    _line.lineColor = [UIColor app_blue];
    _line.labelPosition = ChartLimitLabelPositionRight;
    _line.valueFont = [UIFont systemFontOfSize:10.0];
}

/*
 *  Method to setup data for the BarChart graphic
 *
 *  @param  array   NSMutableArray with array of dictionaries
 *  @param  target  double with target value
 *  @param  granularity NSString ("Monthly", "weekly" or "daily")
 *
 *  @return void
 */
- (void)setDataCount:(NSMutableArray*)array target:(double)target andGranularity:(NSString *)granularity
{
    NSInteger arraySize = [array count];
    NSMutableArray *arrayOy = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *arrayOx = [[NSMutableArray alloc] initWithCapacity:0];

    // get array of values(arrayOy) and keys(arrayOx) from 
    for (NSDictionary *elem in array) {

        [arrayOy addObject: [elem objectForKey:@"value" ]];
        [arrayOx addObject:[elem objectForKey:@"date"]];

    }

    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    NSMutableArray *arrColor = [[NSMutableArray alloc] init];

    for(int i = 0; i < arraySize; i++)
    {
        double val = [[arrayOy objectAtIndex:i]doubleValue];
        [yVals addObject:[[BarChartDataEntry alloc] initWithValue:val xIndex:i+1]];
        if (val < target ) {
            [arrColor addObject:[UIColor red_bar]];
        }else{
            [arrColor addObject:[UIColor green_bar]];
        }
    }

    // Ox label values depends on granularity
    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    [xVals addObject:@""]; // empty value to creat padding from the end
    for (int i = 0; i < arraySize; i++)
    {
        // Formatting Ox axis labels concerning data and granularity
        NSDate* date = [NSDate dateWithTimeIntervalSince1970:[[arrayOx objectAtIndex:i] doubleValue]];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        if ([granularity isEqualToString:@"dayly"] ) {
            [formatter setDateFormat:@"HH:mm"];
        }else{
            [formatter setDateFormat:@"dd/MM"];
        }

        [xVals addObject:[formatter stringFromDate:date]];
    }
    [xVals addObject:@""]; // empty value to creat padding from the end



    BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithYVals:yVals label:@""];


    [set1 setColors:(arrColor)];
    [set1 setBarSpace: 0.90]; // creat a space between of each bar 90%

    set1.drawValuesEnabled = NO;

    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];

    BarChartData *data = [[BarChartData alloc] initWithXVals:xVals dataSets:dataSets];

    _chartView.data = data;

}



via Chebli Mohamed

Bridging Objective-C into Swift Project

I'm trying to put a bridging header file into my Swift project so I can use the Venmo SDK. I've placed the header file where I believe it should go and have added it to the Swift Complier - Code Generation section under build settings.

The bridging header is titled BridgingHeader.h and is directly under the project subsection (would post photo but I don't have enough reputation). It's in the same location as this link: http://ift.tt/1L9KeJV

Under the swift compiler - code generation my path to the bridging header is BridgingHeader.h. Initially I tried to reference the file from the root directory but I still had an error saying error: bridging header '/Users/j9/Desktop/uSell-swift/BridgingHeader.h' does not exist



via Chebli Mohamed

NSInternalInconsistencyException: 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)'

I'm trying to get my app working in Xcode 7 beta but I'm hitting this exception:

NSInternalInconsistencyException: 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)'

Here's the callstack:

0   CoreFoundation                      0x00000001063a89b5 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x0000000105e20deb objc_exception_throw + 48
2   CoreFoundation                      0x00000001063a881a +[NSException raise:format:arguments:] + 106
3   Foundation                          0x00000001036f8b72 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4   CoreLocation                        0x00000001031c7fe3 CLClientGetCapabilities + 8270
5   peach                               0x00000001020c0ee9 -[PeachesBatteryOptimizer initWithDelegate:] + 761
6   peach                               0x0000000102086d25 -[PeachAgent init] + 1141
7   peach                               0x000000010208682c __23+[PeachAgent instance]_block_invoke + 76
8   libdispatch.dylib                   0x00000001068604bb _dispatch_client_callout + 8
9   libdispatch.dylib                   0x000000010684bedc dispatch_once_f + 543
10  peach                               0x00000001020867bb +[PeachAgent instance] + 139
11  peach                               0x0000000102086f4d +[PeachAgent createInstanceWithAppKey:andInternal:useDevApi:] + 93
12  peach                               0x0000000101e2b710 -[ABCAppDelegate createPeachAgent] + 368
13  peach                               0x0000000101e28703 -[ABCAppDelegate application:didFinishLaunchingWithOptions:] + 243
...

Has anyone seen this on iOS 9 beta 5?



via Chebli Mohamed

Equivalent of .map in Swift in Objective C?

Say I have NSArray *x = @[@1, @2, @3, @4];

Now say I want an array like @[@2, @4, @6, @8]

In good ole Swift, I can just do :

xDoubled = x.map({($0) * 2})

Can someone tell me how I can do this in Objective-C without doing -

NSMutableArray *xDoubled = [NSMutableArray new];
for (NSInteger xVal in x) {
    [xDoubled addObject:xVal * 2];
}

?



via Chebli Mohamed

Animation is not coming out correctly

I'm crating a menu that slides from the bottom and up via UIbutton that is pressed to activate the animation. But the animation is coming out incorrectly. It suppose to work like this -https://youtu.be/79ZQDzzOHLk?t=2m52s (but in portrait mode)

But here's how it works after i coded it:
enter image description here

And here's the codes for the animation in the viewcontroller.m

#import "ViewController.h"

    @interface ViewController ()


    @end

    @implementation ViewController
    @synthesize scrollView;

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        draw1 = 0;
        scrollView.frame = CGRectMake(0, 300, 480, 55);
        [scrollView setContentSize:CGSizeMake(480, 55)];

        openMenu.frame = CGRectMake(220, 270, 60, 30);
    }
    - (IBAction)OpenMenu:(id)sender {
        if (draw1 ==0) {
            draw1 = 1;
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            [UIView setAnimationDelay:0.0];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

            [UIButton beginAnimations:nil context:nil];
            [UIButton setAnimationDuration:0.5];
            [UIButton setAnimationDelay:0.0];
            [UIButton setAnimationCurve:UIViewAnimationCurveEaseOut];

            scrollView.frame = CGRectMake(0, 245, 568, 55);
            openMenu.frame = CGRectMake(220, 200, 60, 30);

            [self.view bringSubviewToFront:scrollView];

            [UIView commitAnimations];
        } else {
            draw1 = 0;
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            [UIView setAnimationDelay:0.0];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

            [UIButton beginAnimations:nil context:nil];
            [UIButton setAnimationDuration:0.5];
            [UIButton setAnimationDelay:0.0];
            [UIButton setAnimationCurve:UIViewAnimationCurveEaseOut];

            scrollView.frame = CGRectMake(0, 300, 568, 55);
            openMenu.frame = CGRectMake(220, 270, 60, 30);

            [self.view bringSubviewToFront:scrollView];

            [UIView commitAnimations];
        }
    }
    @end

How do I fix it so it the UIbutton comes at the bottom of the screen in portrait mode and it goes up and down like in the youtube tutorial?



via Chebli Mohamed

Compile Python Code In Obj-C

Hello this question is a little broad but i'm just looking for some basic information.

I have seen multiple I-pad apps that can run simple python code from an app. I just wanted to know how they do this. I know it is possible to run python code embedded in an iOS app but I am confused as to how. Is there any library that would allow me to run embedded python code. I would also like to know what pyobjc really does because I have not seen a full build or what objp does.

I know this is asking for a lot but thank you so much.



via Chebli Mohamed

Crash when try to save an object inside a block. (CoreData could not fulfill a fault for...)

I'm trying to save an object inside the AFNetworking block, but SOMETIMES it crashes with error: CoreData could not fulfill a fault for...

I've read that it's related when I try to manage an object data when it was deleted from the persistent store.

(http://ift.tt/1iEZzmg)

How can I avoid this?


Example:

Line *line = [Line MR_createEntity];
[line setSync:@(SYNC_PROCESSING)];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://test.com/request" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    // CRASH
    [line setSync:@(SYNC_SUCCESS)];
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

} failure:nil];



via Chebli Mohamed

UILabel dynamic height

I know a lot of questions have been asked about it but could not figure out. I have a label that needs its number of lines adusting dynamically. It works with automatic preferred max width, but could not make it work when explicit (I want to support ios7).

The label height does not currently increase

Here is my code:

-(void)viewDidLoad
{
  [super viewDidLoad];
  _feedBackLabel.numberOfLines = 0;
  _feedBackLabel.lineBreakMode = NSLineBreakByWordWrapping;
  _feedBackLabel.preferredMaxLayoutWidth = self.view.frame.size.width - 90;
  [_feedBackLabel setContentHuggingPriority:UILayoutPriorityRequired
                                  forAxis:UILayoutConstraintAxisVertical];
  [_feedBackLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
}

-(void)setFeedback:(NSString*)response
{
  self.feedBackLabel.text = response;
  self.feedBackLabel.hidden = NO;
  [self.feedBackLabel sizeToFit];
}

I have pinned my label with a leading and a trailing space to its superview with priority required. The content hugging and compression resistance are both 750 in the vertical axis. The label has a height constraint with a priority of 500.

Thanks Guillaume



via Chebli Mohamed

vendredi 31 juillet 2015

Bower in Rails app before bower-rails

Inherited a project that has has a rather sparse .bowerrc file and a .bower.json full of dependencies at its root. There is no bower-rails in the Gemfile and thus no Bower Rake tasks.

I'm tempted just to drop in the bower-rails gem and move along but curious how the previous team might have interacted with Bower without bower-rails?

Also, I assume .bower.json pre-dates Bowerfile? OK to migrate .bower.json -> Bowerfile or is there a reason not to?

Seemingly simple questions but Bower 'just works' so I don't tend to fiddle with it much.

Convert mysql to postgres and retain default value

I have a MySQL database that I wish to convert into Postgres. One issue I encountered is to convert tinyint(1) (synonym to boolean) columns into "true" boolean and retain the default value of the MySQL column which can be either 0 or 1 but in Postgres the respective values are true or false. The SQL I'm trying:

ALTER TABLE "payments" ALTER COLUMN "is_automatic" TYPE boolean USING CAST("is_automatic" as boolean);

The error message:

ERROR:  default for column "is_automatic" cannot be cast automatically to type boolean

I would think it would be possible to cast this value somehow. Is this possible to do or do I have to manually add this to the migration script?

Breaking a parameter and save the items separately

I need to save items separately coming from a form of a text field, but my code is saving these items duplicate form.

My controller

def create

  @answer_option = AnswerOption.break_options(answer_option_params)
  @answer_option = AnswerOption.new(answer_option_params)

  respond_to do |format|
    if @answer_option.save
      format.html { redirect_to @answer_option, notice: 'Answer option was successfully created.' }
      format.json { render :show, status: :created, location: @answer_option }
    else
      format.html { render :new }
      format.json { render json: @answer_option.errors, status: :unprocessable_entity }
    end
  end
end

My model

class AnswerOption < ActiveRecord::Base
  belongs_to :question

  def self.break_options(var)
    ugly_answers = var[:content].split /[\r\n]+/
    ugly_answers.each do |answer|
      AnswerOption.create!(content: answer)
    end
  end

end

Thanks!

undefined method for Questions

I am getting the error undefined method `questions' for nil:NilClass when viewing different profiles. I am not seeing why this is an undefined method. Anyone have a clue what I did not do correct?

Logs:

NoMethodError (undefined method `questions' for nil:NilClass): 
app/controllers/users_controller.rb:80:in `show' 

Users Controller:

 def show
    @question = @user.questions.where("answer is not null").order("created_at DESC").page(params[:page]).per_page(3)

Questions Model:

  attr_accessible :answer, :question, :sender_id, :recipient_id, :conversation_id, :twitter, :facebook
  belongs_to :user

  belongs_to :sender,:class_name => 'User',:foreign_key => 'sender_id'

  belongs_to :recipient,:class_name => 'User',:foreign_key => 'recipient_id'

  belongs_to :message

  belongs_to :conversation

  def self.total_answer
      where('answer IS NOT NULL').count
    end

    def self.total_answer_cancelled
        where('answer IS NULL').count
      end

      def self.total_male
        count_of_males = Question.joins(:sender).where(users: {gender: 'male'}).uniq.count
      end

      def self.total_female
        count_of_males = Question.joins(:sender).where(users: {gender: 'female'}).uniq.count
      end

Questions Controller:

  def show
      @question = Question.find(params[:id])
      @questions = Question.order("created_at DESC")
      respond_with(@questions)
    end

    def create
      @question = Question.new(params[:question])
      if @question.save
        @message = current_user.send_message(@question.recipient, @question.question, "You have a question from #{@current_user}") 
        @question.update(:conversation_id => @message.notification.conversation.id)
        render :json => {:notice => 'Your question was saved successfully. Thanks!' }
      else
        render :new, alert: 'Sorry. There was a problem saving your question.'
      end
    end

Rails responding to different formats with AJAX request

I'm trying to understand AJAX requests in Rails. I have a form that I currently submit using remote: true. I want to respond with an HTML redirect if the request is successful, and run an error message with Javascript if it is unsuccessful. However, no matter what the outcome is, the request seems to expect a .html as the return.

respond_to do |format|
  if conversation
    format.html { redirect_to(conversation_path(conversation)) }
  else
    format.js
  end
end

This is called after I save the conversation call on AJAX. On a successful save, the path is correctly rendered. But on an unsuccessful save, it expects the .html and throws an error. How do I accept .js as a response? My goal is to just pop up an error if the call is unsuccessful

Edit: My form_fro:

            <%= form_for :conversation, url: :conversations, html: { class: "conversation-form" } do |f| %>

Rails - Active Record: Find all records which have a count on has_many association with certain attributes

A user has many identities.

class User < ActiveRecord::Base
    has_many :identities
end

class Identity < ActiveRecord::Base
    belongs_to :user
end

An identity has an a confirmed:boolean column. I'd like to query all users that have an only ONE identity. This identity must also be confirmed false.

I've tried this

User.joins(:identities).group("users.id").having( 'count(user_id) = 1').where(identities: { confirmed: false })

But this returns users with one identity confirmed:false but they could also have additional identities if they are confirmed true. I only want users with only one identity confirmed:false and no additional identities that are have confirmed attribute as true.

I've also tried this but obviously it's slow and I'm looking for the right SQL to just do this in one query.

  def self.new_users
    users = User.joins(:identities).where(identities: { confirmed: false })
    users.select { |user| user.identities.count == 1 }
  end

Apologies upfront if this was already answered but I could not find a similar post.

Limit to nested forms with accepts_nested_attributes_for

I have a registration form that creates a User and, via nested forms, needs to work as follows:

Users have Events

Events have EventSessions

EventSessions have a Location

Rails allows me to update as far down as EventSessions because the User model contains: has_many :little_class_sessions, through: :little_classes.

I'm unable to save to Location because it's nested under EventSessions. That's one level too deep for rails, and it throws an exception.

What would be the most correct way to create the Location and update the EventSession with the location_id? Inside the UserController?

Background worker prevents photos from uploading

I have the carrier wave gem installed and I added a background worker to it (carrierwave_backgrounder gem`). The issue is now when I upload a photo it shows an empty box where the photo should be.

Photos model:

  mount_uploader :image, ImageUploader
  process_in_background :image
  store_in_background :image

image_uploader.rb:

  include CarrierWave::ImageOptimizer
  include CarrierWave::MiniMagick
  include ::CarrierWave::Backgrounder::Delay

/initializers/carrierwave_backgrounder.rb:

CarrierWave::Backgrounder.configure do |c|

  c.backend :sidekiq, queue: :carrierwave
end

Migration:

class AddTempToUser < ActiveRecord::Migration
  def change
    add_column :users, :avatar_tmp, :string
  end

Photos controller:

 def create
    @photo = Photo.create(photo_params)
    @photo.user = current_user
    if @photo.valid? and @photo.save!
      flash[:notice] = "Successfully created photos."
      redirect_to :back
    else
      flash[:notice] = @photo.errors.messages[:base].first
      render :action => 'new'
    end
  end

Server logs:

Jul 31 17:28:07 areyoutaken app/web.1:  Processing by PhotosController#create as JS 
Jul 31 17:28:07 areyoutaken app/web.1:  Processing by PhotosController#create as JS 
Jul 31 17:28:07 areyoutaken app/web.1:    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xhE8IGs/FLF+cJvMWMJeC5sUFkGk76Xe6SoWzT8v1Pg=", "photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f7e80662960 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-3-eiq7px>, @original_filename="love.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"love.jpg\"\r\nContent-Type: image/jpeg\r\n">}} 
Jul 31 17:28:07 areyoutaken app/web.1:    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xhE8IGs/FLF+cJvMWMJeC5sUFkGk76Xe6SoWzT8v1Pg=", "photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f7e80662960 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-3-eiq7px>, @original_filename="love.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"love.jpg\"\r\nContent-Type: image/jpeg\r\n">}} 

Trying to "redirect_to :back" after logging in

I'm trying to redirect to the previous page after a user logs in. I am using a bootstrap modal for login/register forms but if someone doesn't have JS enabled on their browser and are taken to the '/login' page, I want to make sure they are redirected to the root url. I know current_page? does not work with POST requests.

I've tried tons of things so the following code is redirecting correctly from the '/login' page to the root url but I am not being redirected to ':back' when logging in using the bootstrap modal.

This is from SessionsController: (PS- I have sessions#new/sessions#create as /login in routes)

def create
    user = User.find_by(email: params[:email]) 
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id

            if request.path === '/login'
                redirect_to '/'
            else
                redirect_to :back
            end

            flash[:success] = "Logged in."

    else
        flash.now[:danger] = "Email and password did not match. Please try again."
        render :new
    end
end

def destroy
    session[:user_id] = nil
    flash[:success] = "Logged out."
    redirect_to '/'
end

Routes.rb:

Rails.application.routes.draw do

root to: 'home#home'

resources :users

get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'

end

How can I refresh the cache of model manually in rake file

How can I refresh the cache of model manually

I can cached pages with fragment,

and refresh it in outside rake task

But I have no idea how to refresh the cache inside the controller for fetching data from DB.

How could I refresh the cache in Rake file

def get_max_and_min_routes(airline_name, from, to)
  Rails.cache.fetch("I_AM_CACHE_KEY") do
    FETCH_FROM_DB
  end
end

rake file

action_controller = ActionController::Base.new
action_controller.expire_fragment("body_header")
action_controller.expire_fragment("index")
action_controller.expire_fragment("welcome_index_controller")
action_controller.expire_fragment("footer")

index.haml

- cache("index", skip_digest: true) do
  = render "historical_prices"
= render "common/recently_changed_prices"

RSpec - ActiveRecord::RecordNotFound when testing templates

I'm trying to test that my templates are rendering but can't seem to figure out why its not registering the ID of my stubbed instance. What do I have to do to get a correct path?

describe RestaurantsController do
  let(:restaurant) { FactoryGirl.build_stubbed(:restaurant) }

  describe "GET #show" do
    before { get :show, id: restaurant.id }
    it { should render_template('show') }
  end
end

Error:

1) RestaurantsController GET #show 
     Failure/Error: before { get :show, id: restaurant.id }
     ActiveRecord::RecordNotFound:
       Couldn't find Restaurant

Dokku push error

After several try to push an app to a dokku instance . i keep receiving this error.I've already search both github and stackoverflow for similar issues but none of them resolve it.I have check my css folders and files for any issue .Unable to pinpoint where the error coming from. If anybody have an idea to resolve it . please share.

 NoMethodError: undefined method `[]' for nil:NilClass                                                                                                                                 
       (in /tmp/build/app/assets/stylesheets/application.css)                                                                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:63:in `sprockets_context'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:14:in `image_path'                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/funcall.rb:113:in `_perform'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `block in _perform'                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `map'                                                                                              
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `_perform'                                                                                         
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:298:in `visit_prop'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map'                                                                                       
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `visit_children'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'                                                               
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:121:in `with_environment'                                                                      
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:108:in `visit_children'                                                                        
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `block in visit'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map' 

ActionController::ParameterMissing in SubjectsController#update

I'm a beginner in RoR. I'm taking the course in lynda.com by Kevin. I'm doing the CRUD in RoR. When I do delete operation it is showing the error

ActionController::ParameterMissing in SubjectsController#update

param is missing or the value is empty: subject

subjects_controller.rb

class SubjectsController < ApplicationController

def index
    render('index')
end

def list
    @subjects = Subject.order("subjects.position ASC")
end

def show
    @subject = Subject.find(params[:id])
end

def new
    @subject = Subject.new(:name => 'username')
end

def create
    @subject = Subject.new(params.require(:subject).permit(:name, :position, :visible))
    if @subject.save
        redirect_to(:action => 'list')
    else
        render('new')
    end
end

def edit
    @subject = Subject.find(params[:id])
end

def update
    @subject = Subject.find(params[:id])
    if @subject.update(subject_params)
        redirect_to(:action => 'show', :id => @subject.id)
    else
        render('edit')
    end
end

def delete
    @subject = Subject.find(params[:id])
end

def destroy
    @subject = Subject.find(params[:id])
    @subject.destroy
    redirect_to(:action => 'list')
end

private
def subject_params
  params.require(:subject).permit(:id, :name, :position, :visible)
end

The highlighted lines of error are

if @subject.update(subject_params)

and

 params.require(:subject).permit(:id, :name, :position, :visible)

delere.html.erb

<%= link_to("<<Back to List", {:action => 'list'}, :class => 'back-link') %>
<%= form_for(:subject, :url => {:action => 'destroy', :id => @subject.id}) do |f| -%>
    <p>Are you sure that you want to delete this subject permanently?</p>
    <p class="reference-name"><%= @subject.name %></p>

    <div class="form-buttons">
        <%= submit_tag("Delete Subject") %>
    </div>
<% end %>

edit.html.erb

<%= link_to("<<Back to List", {:action => 'list'}, :class => 'back-link') %>

<%= form_for(:subject, :url => {:action => 'update', :id => @subject.id}) do |f| %>

    <table summary="Subject from fields">
        <tr>
            <th>Name</th>
            <td><%= f.text_field(:name) %></td>
        </tr>
        <tr>
            <th>Position</th>
            <td><%= f.text_field(:position) %></td>
        </tr>
        <tr>
            <th>Visible</th>
            <td><%= f.text_field(:visible) %></td>
        </tr>
    </table>

    <div class="form-buttons">
        <%= submit_tag("Update Subject") %>
    </div>
<% end %>

Any ideas? Thank you in advance.

Rails routing with REST api and mobile client

Hello I have a standard rails app with some endpoints that serve json format, ad I have the contraint of having them with api-dev, this works great locally but unfortunatly does not play along very well with a mobile client that needs to fetch it through the network but if I try to point to specific ipaddress of course it won't load because the constraint requires a subdomain (api-dev),

Is it possible in rails to have the constraint and by default allow the endpoint to be hit?. BTW I also have a webclient in the same project and it has a subdomain constraint of dashboard.

Setitng custom field values doesn't work with Paranoia

I have been trying to set up Paranoia with my project. I have a deleted_at column and another column status which is equal to 2 when it's deleted.

Model Class

class Account < ActiveRecord::Base

  acts_as_paranoid column: :status, sentinel_value: 1

  def paranoia_restore_attributes
    {
      deleted_at: nil,
      status: 1
    }
  end

  def paranoia_destroy_attributes
    {
      deleted_at: current_time_from_proper_timezone,
      status: 2
    }
  end 
end

But when I perform destroy or restore, it doesn't seem to change the status value.

How many rails instances does delayed job initialize if running multiple pools

I'm running Delayed Job with the pool option like:

bundle exec bin/delayed_job -m --pool=queue1 --pool=queue2 start

Will this spawn one OR multiple rails environments? (ie: will it spawn one environment for all the pools or will every pool gets its own rails environment)?

When testing locally it seemed to only spawn one rails environment for all the pools.

But I want to confirm this 100% (esp on production).

I tried using commands like these to see what the DJ processes were actually pointing to:

ps aux, lsof, pstree

Anyone know for sure how this works, or any easy way to find out? I started digging through the source code but figured someone prob knows a quicker way.

Thanks!