jeudi 13 août 2015

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

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

how to handle ContentSizeCategoryDidChangeNotification more elegant

I have a navigation bar, and set its title with preferredFontForTextStyle, And register for UIContentSizeCategoryDidChangeNotification, but every time, when deal with this notification, I have to reset the titleTextAttributes of the navigation bar to get the title bar updated when I change the Lager Text in accessibility in settings, I just want to know if there is a elegant way to update the title, the code is just below:

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.navigationBar.titleTextAttributes = [
        NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
        NSForegroundColorAttributeName: List.Color.Gray.colorValue
        ]

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleContentSizeCategoryDidChangeNotification:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
   }

    // MARK: Lifetime

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
    }

    // MARK: Notifications

    func handleContentSizeCategoryDidChangeNotification(_: NSNotification) {
        navigationController?.navigationBar.titleTextAttributes = [
        NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
        NSForegroundColorAttributeName: List.Color.Gray.colorValue
        ]
    }

PS. I tried to call setNeedsLayout() and call layoutIfNeeded() of the navigation bar, but it doesn't update the title font, the upper method is fine, but i want a more elegant solution, like call a method from apple.

Thanks



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

PersonViewController in TabBarController

I have a UITabBarController with three tabs. When a certain one is pressed, I'd like the user to immediately see a person view controller (an instance of the ABPersonViewController class).

I don't want to just use the presentViewController() method with a person view controller as a parameter because this results in a lag, when the user can see the underlying view controller from which it's presented.

I also can't make the view controller inherit from ABPersonViewController, because it's set by Apple so that it can't be subclassed. Is there a way I can accomplish this?



via Chebli Mohamed

How do I fit a UISearchBar in a UIBarButtonItem?

I'm using a UISearchController in iOS 8 and when I make its UISearchBar my table's header view everything is fine. However now I need it in my UINavigationBar's left bar button (can't be the title view because of the vertical centering when I enlarge the nav bar). When I wrap the UISearchBar in a UIBarButtonItem it is larger than the width of the screen.

off screen search bar

I think it is related to my view controller initialized from a storyboard with size classes enabled which means my frames are not set till viewDidLayoutSubviews. However I had the same issue with my segmented control in a toolbar and I just called sizeToFit on the toolbar in viewDidLayoutSubviews and that fixed the toolbar. When I do the same for the search bar it still draws partly off screen. Apple does this in some of their iPad apps but how?

Note: I can hack it to get it all on screen but I have to wrap it in another view but then the color is off and it just seems wrong and I think the animation is off.



via Chebli Mohamed

Swift: Screenshot without Tab Bar

I know it's fairly easy to take a screenshot of the entire screen, with or without the navigation and status bars, using a UIGraphicsImageContext but is there a way to take one (or crop one) so that the navigation bar is visible, but the status bar and tab bar are not visible?



via Chebli Mohamed

ios Google Map - how to get my device location without zooming to the camera

I am working on the button to get my location regularly. When it comes to the implementation, the device will let Google Map camera being center of the map regularly even without using GMSCameraUpdate to focus. Would you please tell me what to enhance so that we can regularly get the updated device location without camera zooming?

The below is my working on triggering the zooming after onClick

 if(self.myMapView.myLocation !=nil){
        [self.locationManager stopUpdatingLocation];
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.2];
        GMSCameraUpdate *move = [GMSCameraUpdate setTarget:self.myMapView.myLocation.coordinate  zoom:self.myMapView.camera.zoom];
        [self.myMapView animateWithCameraUpdate:move];
        [CATransaction commit];
    }

Delegate after getting location

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{
    CLLocation *location = [locations lastObject];


    if(location==nil){
        location = self.myMapView.myLocation;
    }

    myDeviceLocation = location;

    NSLog(@"adasdads zoom ");
    if (markera == nil) {
        markera = [[GMSMarker alloc] init] ;
        markera.position   = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
        markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow

        markera.map = self.myMapView;


    }else {
        [CATransaction begin];
        [CATransaction setAnimationDuration:2.0];
        markera.position = location.coordinate;
        markera.icon = nil;
        [CATransaction commit];

    }

    GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17];
    [self.myMapView animateWithCameraUpdate:move];
}



-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)statusX {

    NSLog(@"status  : %d" , statusX);
    if (status == kCLAuthorizationStatusDenied) {
        //location denied, handle accordingly
        NSLog(@"denied ");

    }
else if (statusX == kCLAuthorizationStatusAuthorized) {
    //hooray! begin startTracking
    NSLog(@"proceed ");
    dispatch_async(dispatch_get_main_queue(), ^{
        self.myMapView.myLocationEnabled = YES;
    });



}else   if (statusX == kCLAuthorizationStatusAuthorizedAlways || statusX == kCLAuthorizationStatusAuthorizedWhenInUse) {
    self.myMapView.myLocationEnabled = YES;

    NSLog(@"gogogo ");
    dispatch_async(dispatch_get_main_queue(), ^{
      //  self.myMapView.myLocationEnabled = YES;
    });



via Chebli Mohamed

iOS Google Map Construct the ruler to show the scale

I am trying to create the map scale ruler on Google Map to show the scale ratio (1 cm to XXXX m ). The custom ruler should works like what Google map scale ruler is. When it comes to the testing, I have found that the number is always changing and increases linearly when zooming in or out. I know the Google map ruler does not want this happen to report fixed value until zoom level overflow happens. Could you please tell me how to enhance it ?

The below is my working

- (double ) mapViewRation :(GMSMapView*)mapView idleAtCameraPosition:(GMSCameraPosition*)position
{
    CLLocationCoordinate2D topLeft = mapView.projection.visibleRegion.farLeft;
    CLLocationCoordinate2D bottomLeft = mapView.projection.visibleRegion.nearLeft;
    double lat = fabs(topLeft.latitude - bottomLeft.latitude);
    double mpp = cos(lat * M_PI / 180) * 2 * M_PI * 6378137 / (256 * pow(2, mapView.camera.zoom));
    double distance = mpp * mapView.frame.size.width;
    return distance; 
}




-(void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition*)position {

    // handle you zoom related logic

    NSLog(@"zoom :  %f"  , position.zoom );

    double asK =   [self mapViewRation : self.myMapView  idleAtCameraPosition : position ];

    double aasK=   fmod(asK, 300);
    UIView* lineView;
    if(lineView==nil){
        lineView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 400 , 1)];
        lineView.backgroundColor = [UIColor blackColor];
    }

    CGRect make = CGRectMake(100, 200, 400-aasK , 1) ;
    [lineView setFrame:make ];
        UILabel* zeroLabel;

    if(zeroLabel==nil){
        zeroLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 400-aasK, 10)];
        [zeroLabel setTextColor:[UIColor blackColor]];
        [zeroLabel setBackgroundColor:[UIColor clearColor]];
        [zeroLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
    }
    [zeroLabel setText:[NSString stringWithFormat:@"%.1f" ,1.0f]];

        UILabel* numberLabel;
    if(numberLabel==nil){
        numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(380-aasK, 10, 400-aasK, 10)];
        [numberLabel setTextColor:[UIColor blackColor]];
        [numberLabel setBackgroundColor:[UIColor clearColor]];
        [numberLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
    }
    CGRect maaake = CGRectMake(380-aasK, 10, 400-aasK , 10) ;
    [numberLabel setFrame:maaake ];
    [numberLabel setText:[NSString stringWithFormat:@"%f" ,position.zoom]];

    [lineView addSubview:numberLabel];
    [lineView addSubview:zeroLabel];
    [self.view addSubview:lineView];




}



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

- (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

Reorder Uitableview with Parse Objects?

I am trying to figure out how to reorder my Tableview of parse objects and get them to stay.

  1. I can get the tableview items to move around but the order doesn't save and reverts back to the original order as soon as i leave the Viewcontroller and go back. I have the tableview being populated from a query every time it loads.

  2. Need to figure out how to save the new index order back to parse. Not sure how to do that..here is some of the code I'm working with... or the lack there of.

I have seen people rearrange a static array but i haven't found information on rearranging a dynamic parse query...thanks in advance!

 var thisArray:[PFObject] = [PFObject]()

 override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
 }

 override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

    //How do I rearrange the parse objects on the backend?
 }



via Chebli Mohamed

Stellar Parallax to run on desktop, static image on mobile device

My website is using Stellar.js to create a parallax effect on a number of images that span the width of the users screen. Everything is working nicely on desktop across all browsers of tested. The problem is on iOS or generally mobile devices. My iPad currently shows a blank space where the parallax should be. I have read about ways to get the parallax effect to work on iOS - but it seems to have a big impact on performance. So, I would prefer if I could keep the parallax effect on desktop - and replace the parallax effect with a centered static image with the same position/dimensions for mobile devices. Anyone able to help me with how to achieve this? I saw a post on how to disable Stellar on mobile devices - but this still does not replace the parallax image with a static image instead.

MY CSS FILE
/* Separator About - Parallax Section */
.sep {
        background-attachment: fixed!important;
        background-position: 50% 0!important;
        background-repeat: no-repeat!important;
        width: 100%!important;
        height: 180px!important;
        position: relative!important;
        -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

}
.about {
background-image: url(../img/about-sep.jpg);
MY HTML FILE
<! -- ABOUT SEPARATOR -->
        
 
    <div class="sep about" data-stellar-background-ratio="0.5"></div>
        </div>
    </div>


        <script src="assets/js/jquery.stellar.min.js"></script>

<script>
                        
                $(function(){
                        $.stellar({
                                horizontalScrolling: false,
                                verticalOffset: 40
                        });
                });
                </script>
</body>


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

API for app developers

I am thinking about building an app but I don't have server side skills and don't want to spend time building the API side.

Do you know if there is any service out there on which I could build a simple database (users, objects for each users, etc) and API for myself to use?

Thank you, Jon



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

unwind segue and dealloc

I am trying to understand unwind segue process.

Is dealloc method of the source view controller called when unwind segue performed like UINavigationController back button process?

If not, does that mean a memory leak?



via Chebli Mohamed

json with a foreign language swift

I'm using an API of a website to make an app for them , the app should send an SMS to the client after the client chose an item , the problem is when I try to send a message using the website api , if the message in english the app send it correctly but if it's in another language (in my case arabic) the app doesn't send the message

I tried to use the link with the arabic message in safari and it sent the message successfully , but in the app it doesn't work unless the message is in English

here is my code :

var link = "http://ift.tt/1L9P360"
        println(link)
        message.text = "\(link)"
        if let url = NSURL(string: link){
            println(url)
            var dataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
                if(error != nil){
                    println("Error: \(error.localizedDescription)")
                }else{
                    var jsonError = NSError?()
                    if let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary {
                     println(jsonData)
                    }
                }
            })



            dataTask.resume()
        }



via Chebli Mohamed

Crashing on Ios jailbroken iphones

I created an app that works on jailbroken iphones, my problem is that it works fine on about 80% of users but it is crashing on the other 20% users iphones, the app uses a server, no ios dependency for the crash and no specific iphone to crash on, how can i investigate this issue to make it work on all iphones ?

In addition on my iphone it wokrs fine and also on simulator.



via Chebli Mohamed

Mach-O Linker error when trying to setup Google Analytics in xcode

So I'm trying to get Google Analytics installed inside of my app and have been following the instructions from Google located here http://ift.tt/1LymQan.

My Podfile looks ike this:

 source 'http://ift.tt/1czpBWo'
 platform :ios, '8.0'
 use_frameworks!
 pod 'Google/Analytics', '~> 1.0.0'
 pod 'Google-Mobile-Ads-SDK'

Now everything ran fine after installing pod, but when I added this snippet of code to my AppDelegate.swift file, the app failed to compile.

    // Configure tracker from GoogleService-Info.plist.
    var configureError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

   // Optional: configure GAI options.
    var gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release

This is causing the following compile errors:

Undefined symbols for architecture arm64: "_OBJC_CLASS_$_GAI", referenced from: __TMaCSo3GAI in AppDelegate.o "_OBJC_CLASS_$_GGLContext", referenced from: __TMaCSo10GGLContext in AppDelegate.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any idea how to fix this?



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

UILabel variable needs to be an Optional Double but I don't want the the label to display optional(valueOfNumber)

I'm trying to complete the CS193P Course independently. I am on assignment 2 of the course and part of the assignment asks for me to do the following:

"Change the computed instance variable displayValue to be an Optional Double rather than a Double"

I was able to change displayValue to be an Optional Double, but now my UILabel which shows the displayValue now will display the optional value instead of the double value (which makes sense).

Example:

5 (then press enter) will display a value of Optional(5.0) in the UILabel.

Here is what I tried:

I determined that result and displayValue! will return a double.

I tried changing display.text = result to display!.text! = result but that did not fix the issue.

Here is a snippet of my code, I think you shouldn't need any more but please comment if you think I should show something else!

P.S. the name of the display is display

@IBAction func enter() {
    if let result = brain.pushOperand(displayValue!) {
        displayValue = result
    } else {
        displayValue = 0
    }
}

var displayValue: Double? {
    get {
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display!.text! = "\(newValue)"     //display is the UILabel
    }



via Chebli Mohamed

Compression framework ios9

I have some NSData that is stored with the DEFLATE compression protocol?

DEFLATE Compression Method DEFLATE is a lossless compressed data format that compresses data using a combination of the LZ77 algorithm and Huffman coding, with efficiency comparable to the best currently available general-purpose compression methods. The data can be produced or consumed, even for an arbitrarily long sequentially presented input data stream, using only a priority-bounded amount of intermediate storage. The format can be implemented readily in a manner not covered by patents. Specifications for DEFLATE can be found in RFC 1951 - DEFLATE Compressed Data Format Specification, May 1996.

If I understand it correctly in IOS9 there is a new Compression Framework which "might" handle this case. The documentation lists the following supported algorithms: LZFSE, LZ4, LZMA, and ZLIB level 5.

I'm not sure but I believe ZLIB supports the LZ77 Deflate algorithm. The question I have is how do I actually use this framework:

So I believe the function i want to use is compression_decode_buffer

@available(iOS 9.0, *)
public func compression_decode_buffer(
    dst_buffer: UnsafeMutablePointer<UInt8>, 
    _ dst_size: Int, 
    _ src_buffer: UnsafePointer<UInt8>, 
    _ src_size: Int, 
    _ scratch_buffer: UnsafeMutablePointer<Void>, 
    _ algorithm: compression_algorithm) -> Int

but I'm not sure exactly how to utilize this algorithm.

So from reading the header it looks like i need an input size dst_size: bytes.size and output size a inputBuffer an &outputbuffer and a compression algorithm

dst_buffer: UnsafeMutablePointer, _ dst_size: Int, _ src_buffer: UnsafePointer, _ src_size: Int, _ scratch_buffer: UnsafeMutablePointer, _ algorithm: compression_algorithm) -> Int

Assuming i have some sample data (see below)

let bytes : [UInt8] = [ .... ]  // see below

compression_decode_buffer(
  <DST_BUFFER>,
  <DST_SIZE>, 
  bytes, 
  bytes.count, 
  <SCRATCH_BUFFER>, 
  COMPRESSION_ZLIB
)

Where i'm at a loss is as to what goes into , , .

Any suggestions?

Sample Data

let bytes : [UInt8] = [0x7e, 0x07, 0x07, 0xff, 0xff, 0x41, /* <1~....A */
    0x10, 0x33, 0x51, 0x3e, 0x94, 0xb2, 0xa0, 0x27, /* .3Q>...' */
    0x80, 0x00, 0x21, 0x65, 0x26, 0xd8, 0x22, 0x10, /* ..!e&.". */
    0x2c, 0xd5, 0x99, 0x00, 0x00, 0x44, 0xbb, 0xd4, /* ,....D.. */
    0x54, 0x38, 0xf5, 0x01, 0x36, 0xd1, 0x20, 0x2c, /* T8..6. , */
    0xd5, 0x99, 0xbb, 0x1c, 0xaf, 0xc3, 0x2c, 0x60, /* ......,` */
    0xcb, 0x0c, 0x79, 0xcb, 0x76, 0xa0, 0x84, 0xd5, /* ..y.v... */
    0x99, 0x83, 0x1c, 0xaf, 0xc3, 0x2c, 0x60, 0x35, /* .....,`5 */
    0x66, 0x60, 0x49, 0x76, 0x60, 0xc7, 0x5b, 0xf3, /* f`Iv`.[. */
    0xce, 0x05, 0x08, 0x3a, 0x04, 0x13, 0x4a, 0x00, /* ...:..J. */
    0x92, 0x05, 0x08, 0x17, 0x14, 0x68, 0x31, 0xc3, /* .....h1. */
    0x1c, 0xb2, 0xc3, 0x1e, 0x72, 0xdd, 0xe0, 0x00, /* ....r... */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ........ */
    0x00, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, /* ....'... */
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, /* .......0 */
    0x8e, 0x7e]



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

Why is Core Data Model URL (modelURL) returning as nil?

When I create a new project with CoreDataModel created by XCode, all is well. However, I added a core model file to my project and the "core data stack" code. The code is properly getting invoked, however, the model's URL is nil. I have tried to examine the project and cannot determine if the model file is not properly added, or compiled, or if the URL just cannot be found.

Help me debug and resolve.

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];

modelUrl returns as 'nil.'



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

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

skscene freeze's after cancelling or buy request in InAppPurchasing

All I think this question is new to stackoverflow.

My question is when I tap on purchasing more coins and then cancel that purchase requst after that skscene in sprite kit does not behave as expected.

Before tap on any more button option everything works great, I can easly back to main manu. But after making or tapping more coins option and then cancel that request my skscene stuck, my skscene does not go away but before tapping I was easily able to go back with my expected skscene.

Is it storekit.framework bug? because I'm not getting the thing why after the user cancel the request skscene stuck?

Could any body know why this happening, or I want to let you know that [[SKPaymentQueue defaultQuequ] finishTransition:..]; also applied in both purchased or in failed condition?



via Chebli Mohamed

How come I can add a group to address book in the iOS simulator, but not the device?

My question is very simple: how come the code below works when I use the simulator, but not the device?

I've used two iPad Airs on a deployment target of 8.2 and 8.4, and an iPad Mini (don't know which one, but relatively new) on 8.2, and none of them are able to add a group.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    ABAddressBookRef addressBook;
    bool didSave;
    CFErrorRef error = NULL;

    addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    // If you get some error when trying to add a contact, make sure it's not a permission issue

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {

        if (granted) {

            [self createNewGroup:@"New Group"];
        }

    });

//    [self createNewGroup:@"New Group"];

}

-(void)createNewGroup:(NSString *)groupName
{
    CFErrorRef error = NULL;
    bool didSet, didAdd, didSave;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    if (error) {
        NSLog(@"Error: %@", error);
    }

    ABRecordRef newGroup = ABGroupCreate();

    didSet = ABRecordSetValue(newGroup, kABGroupNameProperty, (__bridge CFTypeRef)(groupName), &error);
    if (!didSet) { NSLog(@"Unresolved error while setting group: %@", error); }

    didAdd = ABAddressBookAddRecord(addressBook, newGroup, &error);
    if (!didAdd) { NSLog(@"Unresolved error while adding group: %@", error); };

    didSave = ABAddressBookSave(addressBook, &error);
    if (!didSave) { NSLog(@"Unresolved error while saving group: %@", error); };

    ABRecordID groupId = ABRecordGetRecordID(newGroup);
//    CFRelease(addressBook);
//    CFRelease(newGroup);
//    CFRelease(error);

}



via Chebli Mohamed

I am having an unwanted collision in a complicated simulation, and please help me understand the bit masks in sprite kit

Ok, I am having quite the issue right now! . (If you want to cut to the chase go to the bold section)

I am having an unwanted collision in my simulation...

My simulation has the following groups:

TeethTop (this is a group of objects)
TeethBottom (this is a group of objects)
Ball (the main object that is moved in the game)
Line (one line that is drawn occasionally only to detect if user swiped to a tooth)
Boundries (boundaries of screen)

Here are the rules I need

  • I need SKcontacts generated when
    • ball hits any teeth (top or bottom)
    • TeethTop hits any teeth
    • Line hits any teeth
  • As far as physical contacts and reactions (who can hit who and have physics simulated)
    • The line can not impede movement or hit the ball
    • The ball must land on the teeth but never move the teeth
    • No tooth must ever physically move due to physics
    • No tooth must ever react to a contact with another tooth
    • The ball needs to never pass through the boundaries
  • Ill throw in gravity
    • The ball is the only thing that reacts to gravity
  • Things that are dynamic (not in code)
    • The ball is dynamic because it reacts to gravity and hitting other teeth
    • Everything else stays put no matter what (however I had to tell the teeth that they were dynamic so I could have SKPhysicsContacts when the top hits the bottom)

Basically what happens is their are two rows of teeth, top and bottom. And they do their thing and become sorta a stage. The walls are the same way. The ball moves around inside the mouth sorta like a plat-former hitting and bounding off teeth. On swipes a SKPhysicsNode line is created following the swipe and detecting which tooth the user swiped towards (**** MABYE their is a better way then making a SKPhyiscsNode for the swipe line... I still need to detect if the user swiped in the direction of a tooth). And everything is dandy for awhile, then the mouth closes and stops when a tooth from the top hits a tooth from the bottom.

I had things all fine and dandy with things set as thus

BottomTeethGroup = 10
TopTeethGroup = 31
playergroup = 2
wallgroup = 1
lineleart = 99

  • Top Teeth
    • affectedbygravity = false
    • collisionbitmask = 0
    • categorybitmask = BottomTeethGroup
    • contacttTest = TopTeethGroup
    • dynamic = false
  • Bottom Teeth
    • affectedbygravity = false
    • collisionbitmask = 0
    • categorybitmask = TopTeethGroup
    • contacttTest = BottomTeethGroup
    • dynamic = false
  • Ball
    • affectedbygravity = false
    • the collision bit mask is never set so it collides with everything
    • categorybitmask = playergroup
    • contacttTest = playergroup
    • Dynamic = true
  • Boundaries
    • categorybitmask = wallgroup
    • dynamic = false
  • Line
    • collisionbitmask = 0
    • categorybitmask = lineleart
    • I have tried setting physics properties to crazy values but I just cant get the ball to pass through

The problem arises when I add the line. Everything with detection works fine UNTIL you add the line. Unfortunately the ball collides with the line creating a physical reaction which just isn't good! The ball should not physically collide with the line!

The way I see it their are some options - Make is to the ball passes through the line, or ignores collisions between the two - Find a different way to detect which tooth the player swiped at (the current method is flawed anyway because the line will detect multiple teeth, just because it has a slope and doesn't stop once it hits the first). I have the coordinates of the start and end and the direction if someone has a better way. - Probably if we could make it so the top teeth and bottom teeth only have physical contact with ones from the other side then things would get easier. - Make it look like the ball is passing through the line

Edit: Perhaps my definitions of things are flawed so here is how I think contacts work - collisionbitmask: will only collide with other objects that have the number you specify after it. If 0 then it collides with no objects, if not set then it collides with all
- categorybitmask: defines what category is, if an object has a category test bit mask with this value then a SKPhysics contact will be created, however their might not necessarily be a physics reaction
- contactTest: If it hits and the other object has the same categorybitmask as the one set here a SKphysics contact will be made - dynamic objects have physical reactions when they hit other dynamic objects, or non dynamic objects. SKPhysicsContacts are written up for all collisions - non dynamic objects will not move in any collision, and will only write up SKPhysicscontacts if the other object is static. Two non dynamic objects are not expected to collide. Please let me know if anything I said in that list was wrong.

Thanks so much!

List of solutions I have tried:

  • Lines collisionbitmask not set (same problem)
  • Cavities collisionbitmask set to 0 (falls through random teeth however it doesn't collide with the line but still generates a SKPhysicsContact)
  • All teeths' collision bit mask set to 4 (A BIIG MESS)
  • Top teeth collision bit mask set to 2 and bottom to 4 (less of a mess and when cavity hits a tooth it drifts like its in 0 g (it is in 0 g))

EDIT EDIT EDIT: I have been trying a bunch of things and none of them work. I got fed up and created a new project with four balls. Basically you set each ball to a specific group type and run the simulation. I have it so their are variables at the top for all the categories. If the simulation is set up right (I believe it is) the program WI simulate what would happen if all the values at the top are correct.

You can find the code and project folder here http://ift.tt/1hAtnGr

Could you please try opening up the project or the code from the simulation and try to get the category, physics, and reporting values set correctly so that the simulation follows the rules? You can change what type each object is by setting "var red" or a different color to a different enum value. If you figure it out please let me know.

You can also find the code below

//

//  GameScene.swift

//  CollisionTesting

//

//  Created by Caleb Kierum on 8/13/15.

//  Copyright (c) 2015 BroccoliPresentations. All rights reserved.

//

 

import SpriteKit

enum type

{

    case _toptooth

    case _bottomtooth

    case _ball

    case _line

    case _boundary

    case _none

}

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        

        //The physics categories for each of them

        var topteethcategory:UInt32 = (0x01 << 1)

        var bottomteethcategory:UInt32 = (0x01 << 2)

        var ballcategory:UInt32 = (0x01 << 3)

        var boundriesgroup:UInt32 = (0x01 << 4)

        var linegroup:UInt32 = (0x01 << 5)

        

        //When collision reports should be written up

        var topteethcolisionreport:UInt32 = bottomteethcategory

        var bottomteethcollisionreport:UInt32 = topteethcategory

        var ballcollisionreport:UInt32 = bottomteethcategory | topteethcategory

        var boundriescollisionreport:UInt32 = 0

        var linecollisionreport:UInt32 = topteethcategory | bottomteethcategory

        

        //When they should bounce off of eachother

        var topteethphysics:UInt32 = bottomteethcategory

        var bottomteethphysics:UInt32 = topteethcategory

        var ballphysics:UInt32 = bottomteethcategory | topteethcategory | boundriesgroup

        var boundriesphysics:UInt32 = boundriesgroup

        var linecollisionphysics:UInt32 = linegroup

        

        

        //Here you can set what tope of object each color is

        var blue:type = type._toptooth

        var red:type = type._bottomtooth

        var yellow:type = type._ball

        var green:type = type._none

        

        

        var xy = CGRectGetMidX(self.frame) * 1.5

        var ball1 = SKSpriteNode(texture: SKTexture(imageNamed: "Blue"))

        ball1.position = CGPoint(x: xy, y:CGRectGetMidY(self.frame));

        ball1.size = CGSizeMake(100, 100)

        ball1.physicsBody?.affectedByGravity = false

        ball1.physicsBody = SKPhysicsBody(circleOfRadius: 50)

        ball1.physicsBody?.velocity = CGVector(dx: -100, dy: 0)

        

        var ball2 = SKSpriteNode(texture: SKTexture(imageNamed: "Red"))

        ball2.position = CGPoint(x:xy / 2, y:CGRectGetMidY(self.frame));

        ball2.size = CGSizeMake(100, 100)

        ball2.physicsBody?.affectedByGravity = false

        ball2.physicsBody = SKPhysicsBody(circleOfRadius: 50)

        ball2.physicsBody?.velocity = CGVector(dx: 100, dy: 0)

        

        var ball3 = SKSpriteNode(texture: SKTexture(imageNamed: "Yellow"))

        ball3.position = CGPoint(x:((xy / 4) + xy) / 2, y:CGRectGetMidY(self.frame) / 2);

        ball3.size = CGSizeMake(100, 100)

        ball3.physicsBody?.affectedByGravity = false

        ball3.physicsBody = SKPhysicsBody(circleOfRadius: 50)

        ball3.physicsBody?.velocity = CGVector(dx: 0, dy: 100)

        

        var ball4 = SKSpriteNode(texture: SKTexture(imageNamed: "Green"))

        ball4.position = CGPoint(x:((xy / 4) + xy) / 2, y:CGRectGetMidY(self.frame) * 1.5);

        ball4.size = CGSizeMake(100, 100)

        ball4.physicsBody?.affectedByGravity = false

        ball4.physicsBody = SKPhysicsBody(circleOfRadius: 50)

        ball4.physicsBody?.velocity = CGVector(dx: 0, dy: -100)

        self.addChild(ball1)

        self.addChild(ball2)

        self.addChild(ball3)

        self.addChild(ball4)

        

        

        switch (blue)

        {

        case type._toptooth:

                ball1.physicsBody?.categoryBitMask = topteethcategory

                ball1.physicsBody?.collisionBitMask = topteethphysics

                ball1.physicsBody?.contactTestBitMask = topteethcolisionreport

        case type._bottomtooth:

            ball1.physicsBody?.categoryBitMask = bottomteethcategory

            ball1.physicsBody?.collisionBitMask = bottomteethphysics

            ball1.physicsBody?.contactTestBitMask = bottomteethcollisionreport

        case type._ball:

            ball1.physicsBody?.categoryBitMask = ballcategory

            ball1.physicsBody?.collisionBitMask = ballphysics

            ball1.physicsBody?.contactTestBitMask = ballcollisionreport

        case type._boundary:

            ball1.physicsBody?.categoryBitMask = boundriesgroup

            ball1.physicsBody?.collisionBitMask = boundriesphysics

            ball1.physicsBody?.contactTestBitMask = boundriescollisionreport

        case type._line:

            ball1.physicsBody?.categoryBitMask = linegroup

            ball1.physicsBody?.collisionBitMask = linecollisionphysics

            ball1.physicsBody?.contactTestBitMask = linecollisionreport

        case type._none:

            ball1.position = CGPointMake(100000, 10000)

        }

        

        switch (red)

        {

        case type._toptooth:

            ball2.physicsBody?.categoryBitMask = topteethcategory

            ball2.physicsBody?.collisionBitMask = topteethphysics

            ball2.physicsBody?.contactTestBitMask = topteethcolisionreport

        case type._bottomtooth:

            ball2.physicsBody?.categoryBitMask = bottomteethcategory

            ball2.physicsBody?.collisionBitMask = bottomteethphysics

            ball2.physicsBody?.contactTestBitMask = bottomteethcollisionreport

        case type._ball:

            ball2.physicsBody?.categoryBitMask = ballcategory

            ball2.physicsBody?.collisionBitMask = ballphysics

            ball2.physicsBody?.contactTestBitMask = ballcollisionreport

        case type._boundary:

            ball2.physicsBody?.categoryBitMask = boundriesgroup

            ball2.physicsBody?.collisionBitMask = boundriesphysics

            ball2.physicsBody?.contactTestBitMask = boundriescollisionreport

        case type._line:

            ball2.physicsBody?.categoryBitMask = linegroup

            ball2.physicsBody?.collisionBitMask = linecollisionphysics

            ball2.physicsBody?.contactTestBitMask = linecollisionreport

        case type._none:

            ball2.position = CGPointMake(100000, 10000)

        }

        

        switch (blue)

        {

        case type._toptooth:

            ball3.physicsBody?.categoryBitMask = topteethcategory

            ball3.physicsBody?.collisionBitMask = topteethphysics

            ball3.physicsBody?.contactTestBitMask = topteethcolisionreport

        case type._bottomtooth:

            ball3.physicsBody?.categoryBitMask = bottomteethcategory

            ball3.physicsBody?.collisionBitMask = bottomteethphysics

            ball3.physicsBody?.contactTestBitMask = bottomteethcollisionreport

        case type._ball:

            ball3.physicsBody?.categoryBitMask = ballcategory

            ball3.physicsBody?.collisionBitMask = ballphysics

            ball3.physicsBody?.contactTestBitMask = ballcollisionreport

        case type._boundary:

            ball3.physicsBody?.categoryBitMask = boundriesgroup

            ball3.physicsBody?.collisionBitMask = boundriesphysics

            ball3.physicsBody?.contactTestBitMask = boundriescollisionreport

        case type._line:

            ball3.physicsBody?.categoryBitMask = linegroup

            ball3.physicsBody?.collisionBitMask = linecollisionphysics

            ball3.physicsBody?.contactTestBitMask = linecollisionreport

        case type._none:

            ball3.position = CGPointMake(100000, 10000)

        }

        

        switch (green)

        {

        case type._toptooth:

            ball4.physicsBody?.categoryBitMask = topteethcategory

            ball4.physicsBody?.collisionBitMask = topteethphysics

            ball4.physicsBody?.contactTestBitMask = topteethcolisionreport

        case type._bottomtooth:

            ball4.physicsBody?.categoryBitMask = bottomteethcategory

            ball4.physicsBody?.collisionBitMask = bottomteethphysics

            ball4.physicsBody?.contactTestBitMask = bottomteethcollisionreport

        case type._ball:

            ball4.physicsBody?.categoryBitMask = ballcategory

            ball4.physicsBody?.collisionBitMask = ballphysics

            ball4.physicsBody?.contactTestBitMask = ballcollisionreport

        case type._boundary:

            ball4.physicsBody?.categoryBitMask = boundriesgroup

            ball4.physicsBody?.collisionBitMask = boundriesphysics

            ball4.physicsBody?.contactTestBitMask = boundriescollisionreport

        case type._line:

            ball4.physicsBody?.categoryBitMask = linegroup

            ball4.physicsBody?.collisionBitMask = linecollisionphysics

            ball4.physicsBody?.contactTestBitMask = linecollisionreport

        case type._none:

            ball4.position = CGPointMake(100000, 10000)

        }

        

        

        

        physicsWorld.gravity = CGVector(dx: 0, dy: 0)

    }

    

 

    override func update(currentTime: CFTimeInterval) {

        /* Called before each frame is rendered */

    }

}

 

//nothing set they collide to eachother

//contactTestbitmask has nothing to do with bumping against eachother

//Category is the most important it gives it a type

//The other two decide when reactions happen, either physical or in code

//Collision bitmask is a list of groups that it actually should collide with

//Contacttestbitmask is list of groups that can trigger the code



via Chebli Mohamed

Visual Studio 2015 Remote iOS Build Server Setup - secure mode issue

I am building a hybrid mobile app (Cordova) and I am trying to run my build on iOS.

I have followed the steps in this documentation to setup my connected Mac and I can see that the Mac terminal responding when I try to build my code in visual studio.

My issue is that when ever I enable the remote build server using remotebuild --secure false I get the following error:

Non-secure connection to http://ift.tt/1J3rtnw could not be established. Verify that the build server is not running in secure mode.

I remember reading somewhere that I should enable secure build once then disable it in order to initialize the remote server security configuration. Whenever I try to run in secure build mode remotebuild I would get this error:

Secure connection to http://ift.tt/1h8ao6a could not be established. Verify that the build server is running in secure mode.

I have also attempted to resolve this issue by recreating PIN, generating and resetting the certificate.

How can I resolve this issue?



via Chebli Mohamed

Scroll View in Sprite Kit

I want to make a vertical scrolling view for the level selector on my sprite kit game, I don't know if I have to use UIScrollView or make it using the Sprite Kit framework. Please if anyone knows the best way to do it and how let me know. Thanks.



via Chebli Mohamed

URL Request fatal error: unexpectedly found nil while unwrapping an Optional value

   func upload(URL: String, headers: NSDictionary, print: Upload, completion: (result: String) -> Void) {
    // init paramters Dictionary
    let videoData = NSData(contentsOfURL: NSURL(fileURLWithPath: URL)!)

    var videoParameters: Dictionary<String, AnyObject> = [
        "md5": toString(toString(videoData).md5())
    ]

    // add addtionial parameters


    // example image data
    //let image = UIImage(named: "177143.jpg")
    //  let imageData = NSData(contentsOfURL: NSURL(fileURLWithPath: URL)!)



    // CREATE AND SEND REQUEST ----------

    let urlRequest = urlRequestWithComponents("API-VERSION", parameters: videoParameters, imageData: videoData!)

    Alamofire.upload(urlRequest.0, urlRequest.1)
        .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
            println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
        }
        .responseJSON { (request, response, JSON, error) in
            println(response?.statusCode)
            if(response?.statusCode == 201){

..... }

func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, AnyObject!>, imageData:NSData) -> (URLRequestConvertible, NSData) {

    // create url request to send
    var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "LiamNeason";

    let contentType = "multipart/form-data;boundary=LiamNeason"
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
    mutableURLRequest.setValue("3", forHTTPHeaderField: "Version")
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")


    // create upload data to send
    let uploadData = NSMutableData()

    // add image
    uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.mp4\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Type: */*\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData(imageData)

    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

fatal error: unexpectedly found nil while unwrapping an Optional value

On line

let urlRequest = urlRequestWithComponents("API-VERSION", parameters: videoParameters, imageData: videoData!)

I've tried unwrapping it as ? instead of ! - Creating the variable first

None of the data is nil...

Heading ##



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

Swift - Variable doesn't retain value

I am using AWS to host images for my iOS app. Right now I am trying to list all the objects in an S3 bucket.

Here is my code:

var description = ""
AWSS3.registerS3WithConfiguration(serviceConfig2, forKey: "s3")
AWSS3.S3ForKey("s3").listObjects(objectList).continueWithBlock { (task: AWSTask!) -> AnyObject! in
    if task.error != nil {
        println(task.error)
    }
    if task.result != nil {
        description = task.result!.description
        println(description)
    }
    return nil
}

println(description == "")

The output is true followed by the correct contents of task.result!.description. In other words, the println outside of the continueWithBlock is printing first and description has not been updated at that time.

How am I supposed to do things with description outside of the continueWithBlock?



via Chebli Mohamed

How would I extract data from social media apps?

I just started dipping my feet into iOS development, and I was wondering how apps like InstaFollow and SnapHack get their data from Instagram and Snapchat.

For example, InstaFollow knows who unfollowed a user. How would I also get a user's information (followers, following, pictures). I did my best to search the internet for an answer but didn't know where to begin. I stumbled across something called Open Authorization. Should I look more into this?

When searching the internet for an answer I can across a Snapchat blog saying how snapchat does not have an open API (or something along those lines).

Basically I guess you could say my question is how can one incorporate data from other apps into an app you create?

I know this question is quite vague, but if someone could direct me to where I could further research this, it would be greatly appreciated.



via Chebli Mohamed

Runge-Kutta animation for iOS

Does anyone know of a library that uses the Runge-Kutta 4th-order animation system for springs in iOS? I've tried using Facebook POP but my designers have been disappointed by the accuracy of their animations.

Just wanted to know before I tried writing my own system.

The library should allow for any RK4 based transformations on position, scale, or rotation.

Or am I wrong and Facebook POP actually does use 4th-order Runge-Kutta for their spring animations?



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

Runtime error: dyld: Library not loaded: @rpath/AWSCore.framework/AWSCore

I'm using AWS Mobile Analytics for iOS (2.2.3). After running pod update, I'm getting the following error when trying to run MyApp on a physical device:

dyld: Library not loaded: @rpath/AWSCore.framework/AWSCore Referenced from: /private/var/mobile/Containers/Bundle/Application/4582B679-A162-47CE-80ED-58C8B9BB231B/MyApp.app/MyApp Reason: Incompatible library version: MyApp requires version 2.0.0 or later, but AWSCore provides version 1.0.0

My cocoapods pod file entry for the AWS Mobile Analytics library is:

pod 'AWSMobileAnalytics'

I've tried decrementing the AWSMobileAnalytics version (pod 'AWSMobileAnalytics', '2.2.2'), but I still get the same error. Does anyone know how to get around this?



via Chebli Mohamed

iOS Swift : how to check whether there is Bluetooth device in range of iPhone

iOS, swift How to check "whether there is any Bluetooth device in range of iPhone - Yes or No" . In other words, to check whether the iPhone can find any Bluetooth-RSSI.

Note this question is not checking "connected/disconnected Bluetooth" device. This question is finding whether there is any bluetooth device in the range. Connection is not the concern.

I understand the question seems quite familiar and classic and maybe even simple, but indeed I did not find answer after research. Any help ? Thanks Bill

PS 1 : I tried to use

 func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) { \\check Bluetooth device }

, but unfortunately , the function is simply bypassed when there is no Bluetooth device in range, because RSSI (as the input of the function) does not exist at all when there is no BL device in range.

PS 2: I tried "Get bluetooth devices in range with SWIFT 1" but it seems it only works for OS X while not iOS. Anyway, it does not answer my question.



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

AVPlayerLayer inside UIScrollView Not Zooming To Center

  • I have a UIScrollView *myScrollView which has a UIView *videoView that contains a AVPlayerLayer *playerLayer(Actually a PBJVideoView if anyone is familiar).
  • The AVPlayerLayer is set to AVLayerVideoGravityResizeAspect.
  • myScrollView's delegate's - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView returns videoView.

So if I am looking at a landscape video on a portrait oriented iPhone, it fits the video so that the width matches the iPhone and there is black at the top and bottom.

As the zoomScale goes above 1.0 the video seems biased towards the right side. Like the anchorPoint is maybe (0.75,0.5) - even though it is (0.5,0.5). In other words it zooms into a point to the right of center.

Is there something with the AVPlayerLayer that is causing this issue? I don't have the same problem with a UIImageView?



via Chebli Mohamed

UICollectionView saving null

I have an app that allows a user to upload objects and adds various attributes to that object in a collection view. That part is working fine.

I'm adding a filter to the search feature. I'd like to have a similar collection view that a user can select different tags/cells that I'll then be able to use to filter the results. For some reason however my NSArray is not getting saved. Probably something obvious, but I keep trying to resolve without success.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell;

    ItemFilterCell *aCell = (ItemFilterCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"itemFilterCell" forIndexPath:indexPath];
        aCell.label.text = self.itemFilterPresets[indexPath.section][indexPath.row];
    cell = aCell;
 return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * selectedRows = self.collectionView.indexPathsForSelectedItems;

    for (NSIndexPath * selectedRow in selectedRows) {
        if ((selectedRow.section == indexPath.section) && (selectedRow.row != indexPath.row)) {
            [self.collectionView deselectItemAtIndexPath:selectedRow animated:NO];
        }
    }
    switch (indexPath.section) {
        case 0:
            self.filterSetting.criteria1 = self.itemFilterPresets[indexPath.section][indexPath.row];
            break;
        case 1:
            self.filterSetting.criteria2 = self.itemFilterPresets[indexPath.section][indexPath.row];
            break;
        ....
        default:
            break;
    }
    NSLog(@"criteria1 -----> %@",self.filterSetting.criteria1);
     ....
*********[these all log as null though selected]************

This is correct tho. Just not saving to filterSetting: NSLog(@"criteria1 -----> %@",self.itemFilterPresets[indexPath.section][indexPath.row);

}



via Chebli Mohamed

Swift, Google map fit bound for all the markers

I want to fit all the markers in the google map window with auto zoom.

Below is my code

func loadGoogleMap()
{

    dispatch_async(dispatch_get_main_queue(),
        {
            self.googleMapView.clear()

            self.googleMapView.delegate = self
            var visibleRegion : GMSVisibleRegion = self.googleMapView.projection.visibleRegion()
            var bounds = GMSCoordinateBounds(coordinate: visibleRegion.nearLeft, coordinate: visibleRegion.nearRight)
            var count = 1
            for Prop: Property in self.properties
            {
                if Prop.propLat != ""
                {

                   //  println("lat >>  \(Prop.propLat) lang >> \(Prop.propLang)")
                    var latStr = Prop.propLat
                    var latDbl : Double  = Double(latStr.floatValue)
                    var langStr = Prop.propLang as NSString
                    var langDbl : Double = Double(langStr.floatValue)
                    var marker = GMSMarker()

                    if count == 0
                    {
  //                           let initialLocation =   CLLocationCoordinate2DMake(langDbl,latDbl)
   //                            let initialDirection = CLLocationDirection()
    //                            
    //                            let camera = GMSCameraPosition.cameraWithTarget(initialLocation, zoom: 5)
    //                            self.googleMapView.camera = camera
    //                            
                    }

                    marker.position = CLLocationCoordinate2DMake(langDbl,latDbl)
                    marker.appearAnimation = kGMSMarkerAnimationPop
                    marker.icon = UIImage(named: "red_\(Prop.propSequence)")
                    marker.title = Prop.propBuildingName as String
                    marker.snippet = Prop.propCode as String
                    marker.infoWindowAnchor = CGPointMake(0.44, 0.45);
                    bounds.includingCoordinate(marker.position)
                    marker.map = self.googleMapView
                    count++

                }

            }

            self.googleMapView.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 30.0))

    })

   }

Above swift code is added on view willappear and viewdidload method as well. Can someone please help me what i am doing wrong in the above code.



via Chebli Mohamed