PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label objective-c++. Show all posts
Showing posts with label objective-c++. Show all posts

Monday, December 12, 2022

[FIXED] What is the difference between "foo.bar" and "[foo bar]" in objective C?

 December 12, 2022     objective-c, syntax     No comments   

Issue

I'm following Apple's Objective C MetalKit guide, and this line of code appears here:

MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;

Is there a difference between using view.currentRenderPassDescriptor; and [view currentRenderPassDescriptor];? I've always seen the second option and neither are giving me errors or different results, but it seems strange that they would have both syntax options available for the same purpose.


Solution

The dot syntax is syntactic sugar, merely a newer, more concise, syntax that they subsequently added to the language. The dot syntax and the square brackets are functionally equivalent.

See Dot Syntax Is a Concise Alternative to Accessor Method Calls from Programming with Objective-C:

As well as making explicit accessor method calls, Objective-C offers an alternative dot syntax to access an object’s properties.

Dot syntax allows you to access properties like this:

NSString *firstName = somePerson.firstName;
somePerson.firstName = @"Johnny";

Dot syntax is purely a convenient wrapper around accessor method calls. When you use dot syntax, the property is still accessed or changed using the getter and setter methods mentioned above:

  • Getting a value using somePerson.firstName is the same as using [somePerson firstName]
  • Setting a value using somePerson.firstName = @"Johnny" is the same as using [somePerson setFirstName:@"Johnny"]

This means that property access via dot syntax is also controlled by the property attributes. If a property is marked readonly, you’ll get a compiler error if you try to set it using dot syntax.



Answered By - Rob
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 25, 2022

[FIXED] Where are the system-wide Objective-C modules defined in macOS?

 November 25, 2022     module, objective-c     No comments   

Issue

I was interested to inspect globally available modulemaps of Objective-C language under macOS and was wondering if it's possible to add one myself. Is there a way to know where a particular module (e.g. Foundation) is located?

@import Foundation; // Where this comes from?

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Hello, world!");
    }
    return 0;
}

Solution

Almost all modules are embedded to the corresponding frameworks in the system. For the latest version of macOS at the time of writing (macOS Monterey 12.6 (21G115)) the frameworks can be found under this directory:

/Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks

E.g. Foundation modulemap is located at the path /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/Foundation.framework/Versions/C/Modules/module.modulemap and looks like this:

framework module Foundation [extern_c] [system] {
    umbrella header "Foundation.h"
    
    export *
    module * {
        export *
    }
    
    
    explicit module NSDebug {
        header "NSDebug.h"
        export *
    }
    
    // Use NSItemProvider.h
    exclude header "NSItemProviderReadingWriting.h"
}

The dependencies which were not part of any framework (e.g. libobjc), however, also have modulemaps defined and available under different directory:

/Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include


Answered By - The Dreams Wind
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 6, 2022

[FIXED] How to access the phone contact list and display it in tableview?

 November 06, 2022     abaddressbook, contacts, iphone, objective-c     No comments   

Issue

Such as the Table cell having:

  1. Contact image

  2. Contact name.

I found that we have to use framework:

  1. AddressBook.framework

  2. AddressBookUI.framework

How can I achieve this?


Solution

ABAddressBookRef addressBook = ABAddressBookCreate(); // create address book reference object
NSArray *abContactArray = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); // get address book contact array

NSInteger totalContacts =[abContactArray count];
    
for(NSUInteger loop= 0 ; loop < totalContacts; loop++)
{
    ABRecordRef record = (ABRecordRef)[abContactArray objectAtIndex:loop]; // get address book record
        
   if(ABRecordGetRecordType(record) ==  kABPersonType) // this check execute if it is person group
    {
            ABRecordID recordId = ABRecordGetRecordID(record); // get record id from address book record
            
            NSString *recordIdString = [NSString stringWithFormat:@"%d",recordId]; // get record id string from record id
            
            NSString *firstNameString = (NSString*)ABRecordCopyValue(record,kABPersonFirstNameProperty); // fetch contact first name from address book  
            NSString *lastNameString = (NSString*)ABRecordCopyValue(record,kABPersonLastNameProperty); // fetch contact last name from address book
    }
}

for more check these links

http://developer.apple.com/library/ios/#documentation/AddressBook/Reference/ABPersonRef_iPhoneOS/Reference/reference.html

http://developer.apple.com/library/ios/#DOCUMENTATION/AddressBook/Reference/ABAddressBookRef_iPhoneOS/Reference/reference.html



Answered By - Sadia
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How to set up a has-many relationship in Cocoa?

 October 21, 2022     has-many, iphone, key-value-coding, objective-c, one-to-many     No comments   

Issue

I'm building a (very) simple FTP app in Cocoa, and I need to store information on the different types of servers that are supported. So, I've created a ServerType class, which stores all of the relevant information about a single type of server. I then have a ServerTypes class which is designed to manage all of the ServerType classes that are created.

My question is, how to set up the relationship between the two objects. Is there a preferred method to do so?

Also, since Objective-C doesn't support non-instance classes, where should I create an instance of ServerTypes that will have to be used throughout the entire program? Or is there a better way to do that? I need it to be KVC compliant so That I can bind one of the ServerType properties to an NSPopupBox.

I'm fairly new to Cocoa and Objective-C.


Solution

To manage a relationship between 2 objects, you have 2 ways: composition or inheritance.

You can inherit from a class to create a subclass then you will have a is-a relationship.

If one object contains another as an instance variable then you will have a has-a relationship.

Here, I think it would be the best to use composition where the ServerTypes objects has an array of all server type objects. Objective-C supports non-instance variable (if that's what you mean), by creating static variable. Then you can use it accross the whole program



Answered By - vodkhang
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 29, 2022

[FIXED] How can I get a specific button running on tvOS (AppleTV) to take focus? (Objective C)

 September 29, 2022     focus, objective-c, tvos     No comments   

Issue

The project have some views with different buttons. When I hide a view and show the other view, I can't get the focus on my button.

I think is related to setNeedsFocusUpdate. I have read the Apple doc. There is not any example.

Does anyone know how to do it and put an example (Objective C)?


Solution

You need to override preferredFocusedView, and when you are hiding one view and showing there call this method setNeedsFocusUpdate, your preferredFocusedView implementation should be something like this

- (UIView *)preferredFocusedView
{
    // Add your logic here, it could be more complicated then what is below
    if (view1.hidden)
    {
        return _button;
    }
    else 
    {
        return _button2
    }
}

And if you want to make custom view get focus, override canBecomeFocused method and return true

Edit

You can use add a breakpoint and execute this command po [buttonYouWantToFocus _whyIsThisViewNotFocusable] it will tell you why its not focusable.



Answered By - Adnan Aftab
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to make UISwipeGestureRecognizer work in a view with other gesture recognizers tvOS

 September 29, 2022     objective-c, tvos     No comments   

Issue

My UITapGestureRecognizer gestures work as they supposed to but I've been trying to Add UISwipeGestureRecognizer to my tvOS app but when I test it with the simulator it does not work!

here is my code :

- (void)addScreenControlGesturesRecognizers {
    UITapGestureRecognizer *_oneTapMediaControl = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapMediaControl:)];
    _oneTapMediaControl.numberOfTapsRequired = 1;
    _oneTapMediaControl.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypeSelect]];

    [self.view addGestureRecognizer:_oneTapMediaControl];

    UITapGestureRecognizer *_doubleTapMediaControl = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapControl:)];
    _doubleTapMediaControl.numberOfTapsRequired = 2;
    _doubleTapMediaControl.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypeSelect]];

    [self.view addGestureRecognizer:_doubleTapMediaControl];

    [_oneTapMediaControl requireGestureRecognizerToFail:_doubleTapMediaControl];

    UISwipeGestureRecognizer *_swipeGesturesControl = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureRecognizer:)];
    _swipeGesturesControl.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:_swipeGesturesControl];

}

- (void)handleSwipeGestureRecognizer:(UISwipeGestureRecognizer *)recognizer {
        NSLog(@"Swipe Left"); 
}

Solution

You have to set your gesture recognizer to work simultaneously with other gesture recognizer. Please use UIGestureRecognizerDelegate's method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    return YES;
}


Answered By - SergStav
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What protocol of AllCast use for casting tvOS ?

 September 29, 2022     apple-tv, objective-c, tvos     No comments   

Issue

I'm trying to implement an app like Allcast which can use to scan nearby (Apple TV) and pass image,audio,video through apple tv to show them. But i cant figure it out. What protocol AllCast use ? I tried AirPlay but it can't custom UI like Allcast (Scan device, IP, imagepreview),...

enter image description here

Allcast AppleStore: https://itunes.apple.com/us/app/allcast-cast-photos-music/id943763227?mt=8


Solution

Finally I found a sdk for these stuffs. ConnectSDK is greate. https://github.com/ConnectSDK



Answered By - Son Tieu
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to detect Apple TV Siri Remote button presses?

 September 29, 2022     objective-c, tvos     No comments   

Issue

According to the Apple TV interface guideline, when it comes to games you're supposed to use the menu button as a pause button when you're not at the main menu of the game (in which case it should return to the Apple TV OS menu). However, I can't find anywhere how you're supposed to detect the hard button input from your remote (as opposed to soft buttons on screen).

I did find this short programming guide to using controllers that almost seems to imply that you're supposed to use the remote as a controller in this case, but I can't help but think there's a simpler way. ex.

 -(void)buttonPressBegan:(NSEvent*)event

etc (that's not real... I'm just hoping there's something like that). What is/Is there a sanctioned way of detecting this?


Solution

Apple suggests using a UITapGestureRecognizer to detect when a button is released.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController {
    UITapGestureRecognizer *tapRecognizer;
}

-(void)viewDidLoad {
    [super viewDidLoad];

    tapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    tapRecognizer.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypeMenu]];
    [self.view addGestureRecognizer:tapRecognizer];
}

-(void)handleTap:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        NSLog(@"Menu button released");
    }
}

For a complete list of UIPressType's refer to UIPress Class Reference.



Answered By - Daniel Storm
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I open another application with tvOS?

 September 29, 2022     objective-c, tvos     No comments   

Issue

Does UIApplication:openURL work?

NSString *iTunesLink = @"http://www.youtube.com/watch?v=TFFkK2SmPg4";
BOOL did = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

This does nothing.


Solution

I assume you're wanting to test a Custom URL Scheme. You will want to use canOpenURL to see if the URL can be opened first. canOpenURL returns a BOOL value indicating whether or not the URL’s scheme can be handled by some app installed on the device. If canOpenURL returns YES then you would continue to open the URL with openURL.

YouTube links open the YouTube app by default on iOS devices. This behavior is not yet testable on the new Apple TV as YouTube's app is not accessible in the tvOS beta.

Here's an example of how to use canOpenURL to see if Facebook is installed on an iOS device using its Custom URL Scheme:

Obj-C:

// Check if FB app installed on device
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://profile/355356557838717"]];
}
else {
   // FB not installed
   // Do something else
}

Swift:

// Check if FB app installed on device
if UIApplication.sharedApplication().canOpenURL(NSURL(string:"fb://")!) {
    UIApplication.sharedApplication().openURL(NSURL(string:"fb://profile/355356557838717")!)
}
else {
    // FB not installed
    // Do something else
} 

I'd anticipate that applications such as Facebook, and others, will implement their Custom URL Schemes in the same manner as their iOS counterparts.



Answered By - Daniel Storm
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change UICollectionView zIndex?

 September 29, 2022     ios, objective-c, swift, tvos, uicollectionview     No comments   

Issue

Check the image below. I need to highlight the focused cell such that it is above all the cells in collectionView.
I know I have to change the zIndex of the focused cell. How to do that?
I need the logic. My code is in objective-c.

This is for tvOS but iOS code will also work here I guess.

enter image description here


Solution

Have you tried setting value for cell.layer.zPosition?



Answered By - iOSer
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I force focus to change to a specific view in tvOS?

 September 29, 2022     objective-c, tvos     No comments   

Issue

I am implementing custom code to handle a click on the Menu button on the Siri Remote. How can I force focus to change to my custom menu when pressing the menu button?


Solution

Finally figured it out myself. You have to override the preferredFocusedView property of your UIView or UIViewController.

In Swift it works like this:

func myClickHandler() {
    someCondition = true
    self.setNeedsFocusUpdate()
    self.updateFocusIfNeeded()
    someCondition = false
}

override weak var preferredFocusedView: UIView? {
    if someCondition {
        return theViewYouWant
    } else {
        return defaultView
    }
}

I can't quite remember how to override getters in Objective-C so if someone want to post that I'll edit the answer.



Answered By - Slayter
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to listen to Apple TV Remote in Objective-C?

 September 29, 2022     avplayer, avplayerviewcontroller, objective-c, tvos, uitapgesturerecognizer     No comments   

Issue

This seems like it should be pretty straight-forward but I'm having trouble finding a working example, good documentation, or even many StackOverflow posts that are helpful.

I have a custom view which contains an AVPlayer, like so:

@implementation
{
    @private
    AVPlayerViewController *controller
}

- (id) init
{
    self = [super init];
    if (self)
    {
        controller = [[AVPlayerViewController alloc] init];
        controller.view.frame = self.view.bounds;
        [self.view addSubview:controller.view];
    }
    return self;
}

@end

(I have a few other views like a message that overlays the player, a poster that I display while swapping videos, etc - but this is the basic setup)

When I integrated the IMA SDK, I started to have issues. If you press the pause button on the remote control during an ad, it pauses the ad just fine. But if you press the pause button again it doesn't unpause the ad, but instead unpauses my content player behind the ad. I don't hear any audio, but I know the content player was unpaused because I have ID3 metadata in my video and an NSLog() statement when I hit it, and I begin to see these logs. If I press the pause button again, the logs pause. I press it a fourth time, the logs start up again.

To try and fix this I wanted to bind a listener to the remote's play/pause button and make sure that if I was playing an ad then the ad was resumed, not the content. So I tried adding the following to my init method on my view:

        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self.view action:@selector(tapped:)];
        [tapRecognizer setAllowedPressTypes:@[ [NSNumber numberWithInt:UIPressTypePlayPause] ]];
        [self.view addGestureRecognizer:tapRecognizer];

I then created the following method:

- (void) tapped: (UITapGestureRecognizer *) sender
{
    NSLog(@"Tapped");
}

This isn't being called. I'm pretty confident I made a simple mistake, but the documentation isn't very clear, so I'm not sure what I should be doing instead. The official documentation on detecting button presses uses Swift and says:

    let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
    tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)];
    self.view.addGestureRecognizer(tapRecognizer)

I believe I translated those three lines well. The documentation then doesn't show what the tapped method should look like, but instead goes on a tangent about working with low-level event handling. So to get the appropriate method signature I looked at the documentation on UITagGestureRecognizer which had the following (Swift) example for writing a handler:

func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        // handling code
    }
}

This is why I went with - (void) tapped: (UITapGestureRecognizer *) sender

Still, after all of that, it's not working.

Quick Update

I tried replacing:

initWithTarget:self.view

With:

initWithTarget:controller.view

And:

self.view addGestureRecognizer

With:

controller.view addGestureRecognizer

And this time it looks like something actually happened when I pressed the play/pause button. The app crashed and Xcode gave me the following error:

2019-12-17 12:16:50.937007-0500 Example tvOS App[381:48776] -[_AVPlayerViewControllerContainerView tapped:]: unrecognized selector sent to instance 0x10194e060

So it seems like (correct me if I'm wrong):

  • The AVPlayerViewController has the focus, not my view
  • The gesture recognizer calls the selector on whatever class you register it to, rather than the class that did the registering

So I guess an alternative question to my original would be: How do I allow my class to handle a gesture on some other class (e.g. AVPlayerViewController)?


Solution

The target does not need to equal the view that the gesture recognizer is attached to. You can set the target to MyView but still attach the gesture recognizer to controller.view

To work around the unrecognized selector crash, you need to make sure you're providing the correct object as the target for your gesture recognizer. The way UIGestureRecognizer works is that when the gesture is recognized, it will invoke the given selector on the given target object. In other words, when gesture fires, it's going to perform the equivalent of:

[target selector:self];

(You seem to be treating the target as the view that the gesture will be attached to, which isn't how it works)

So if you implemented tapped: on your class MyView, then the target you pass to the gesture recognizer initializer should be an instance of MyView. You probably want to provide self, not self.view.



Answered By - Justin Voss
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 28, 2022

[FIXED] Why SCNPhysicsBody resets position when set eulerAngles?

 September 28, 2022     apple-tv, objective-c, scenekit, scnnode, tvos     No comments   

Issue

I'm trying to use SceneKit to develop a game for tvOS, and I'm having an issue. When I set the node's eulerAngle before apply an impulse to the physicsBody the node is reset to his original position.

I was expecting to see the nodes moving around on the floor's plane, but on each tap the nodes are moved to the origin position before the impulse is applied.

I'm new at the use of this framework, so I wonder where is the mistake. I'm using the new AppleTV with tvOS 9.0 and XCode 7.1.1

To reproduce it, you can create a new xcode project (Game for tvOS) and replace the GameViewController.m with this code:

#import "GameViewController.h"

SCNNode *ship;
SCNNode *node;
SCNNode *ground;

@implementation GameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // create a new scene
    SCNScene *scene = [[SCNScene alloc] init];
    scene.physicsWorld.gravity = SCNVector3Make(0, -800, 0);

    // create and add a camera to the scene
    SCNNode *cameraNode    = [SCNNode node];
    cameraNode.camera      = [SCNCamera camera];
    cameraNode.camera.zFar = 10000;
    [scene.rootNode addChildNode:cameraNode];

    // place the camera
    cameraNode.position = SCNVector3Make(0, 64, 64);

    // create and add a light to the scene
    SCNNode *lightNode   = [SCNNode node];
    lightNode.light      = [SCNLight light];
    lightNode.light.type = SCNLightTypeOmni;
    lightNode.position   = SCNVector3Make(0, 10, 10);
    [scene.rootNode addChildNode:lightNode];

    // create and add an ambient light to the scene
    SCNNode *ambientLightNode    = [SCNNode node];
    ambientLightNode.light       = [SCNLight light];
    ambientLightNode.light.type  = SCNLightTypeAmbient;
    ambientLightNode.light.color = [UIColor darkGrayColor];
    [scene.rootNode addChildNode:ambientLightNode];

    SCNGeometry *geometry;
    SCNMaterial *material;
    SCNNode *tempNode;
    SCNPhysicsShape* shape;
    SCNPhysicsBody* body;

    //--
    SCNScene *loaded = [SCNScene sceneNamed:@"art.scnassets/ship.scn"];
    tempNode = [loaded.rootNode childNodeWithName:@"ship" recursively:YES];

    geometry = [SCNCylinder cylinderWithRadius:16 height:8];
    shape    = [SCNPhysicsShape shapeWithGeometry:geometry options:nil];

    tempNode.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeDynamic shape:shape];
    tempNode.physicsBody.restitution      = 1;
    tempNode.physicsBody.friction         = 0.25;
    tempNode.physicsBody.categoryBitMask  = 2;
    tempNode.physicsBody.collisionBitMask = 1;
    tempNode.position = SCNVector3Make(32, 32, 0);
    [scene.rootNode addChildNode:tempNode];
    ship = tempNode;

    //--
    geometry = [SCNCylinder cylinderWithRadius:16 height:8];

    material = [[SCNMaterial alloc] init];
    material.diffuse.contents = UIColor.yellowColor;
    geometry.materials        = @[material];

    shape = [SCNPhysicsShape shapeWithGeometry:geometry options:nil];
    body  = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeDynamic shape:shape];

    tempNode = [SCNNode nodeWithGeometry: geometry];
    tempNode.physicsBody                  = body;
    tempNode.physicsBody.restitution      = 1;
    tempNode.physicsBody.friction         = 0.25;
    tempNode.physicsBody.categoryBitMask  = 2;
    tempNode.physicsBody.collisionBitMask = 1;
    tempNode.position = SCNVector3Make(0, 32, 0);
    [scene.rootNode addChildNode:tempNode];
    node = tempNode;

    //--
    geometry = [[SCNFloor alloc] init];

    material = [[SCNMaterial alloc] init];
    material.diffuse.contents = UIColor.blueColor;
    geometry.materials        = @[material];

    shape = [SCNPhysicsShape shapeWithGeometry:geometry options:nil];
    body  = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeKinematic shape:shape];

    tempNode = [SCNNode nodeWithGeometry: geometry];
    tempNode.physicsBody = body;
    tempNode.physicsBody.categoryBitMask = 1;
    [scene.rootNode addChildNode:tempNode];
    ground = tempNode;

    //--
    SCNLookAtConstraint * constraint = [SCNLookAtConstraint lookAtConstraintWithTarget: ground];
    constraint.gimbalLockEnabled = YES;
    cameraNode.constraints = @[constraint];

    // configure the SCNView
    SCNView *scnView = (SCNView *)self.view;
    scnView.scene = scene;
    scnView.allowsCameraControl = NO;
    //scnView.antialiasingMode = SCNAntialiasingModeMultisampling2X;
    scnView.debugOptions = SCNDebugOptionShowPhysicsShapes;
    scnView.showsStatistics = YES;
    scnView.backgroundColor = [UIColor blackColor];

    // add a tap gesture recognizer
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    NSMutableArray *gestureRecognizers = [NSMutableArray array];
    [gestureRecognizers addObject:tapGesture];
    [gestureRecognizers addObjectsFromArray:scnView.gestureRecognizers];
    scnView.gestureRecognizers = gestureRecognizers;
}

- (void) handleTap:(UIGestureRecognizer*)gestureRecognize
{
    float x = (rand() / (float)RAND_MAX) - 0.5f;
    float y = (rand() / (float)RAND_MAX) - 0.5f;
    float speed = (rand() / (float)RAND_MAX) * 300;

    CGPoint velocity = CGPointMake(x, y);
    float angle = [self AngleBetween:velocity And:CGPointMake(1, 0)] + M_PI_2;

    [node.physicsBody applyForce:SCNVector3Make(velocity.x*speed, 0, velocity.y*speed) impulse:YES];
    [ship.physicsBody applyForce:SCNVector3Make(velocity.x*speed, 0, velocity.y*speed) impulse:YES];

    // if comment these lines the problem doesn't appears
    node.eulerAngles = SCNVector3Make(0, angle, 0);
    ship.eulerAngles = SCNVector3Make(0, angle, 0);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (float) AngleBetween:(CGPoint)_origin And:(CGPoint)_destination
{
    float dotProduct = (_origin.x * _destination.x) + (_origin.y * _destination.y);
    float perpDotProduct = (_origin.x * _destination.y) - (_origin.y * _destination.x);

    return -atan2f(-perpDotProduct, dotProduct);
}

@end

If you comment the lines where the euler angles are set (at handleTap method) the problem doesn't appears.


Solution

From Apple's SCNPhysicsBody documentation:

If you change the transform value—or any of the other properties that are components of the transform, such as position and rotation—of a node affected by physics, SceneKit resets the physics simulation for that node.

The physics simulated values are in the presentationNode property. So in your case the way to go is to copy the presentation node's position before applying the transformation, and then write it back:

SCNVector3 nodePosition = [[node presentationNode] position];
SCNVector3 shipPosition = [[ship presentationNode] position];

[node.physicsBody applyForce:SCNVector3Make(velocity.x*speed, 0, velocity.y*speed) impulse:YES];
[ship.physicsBody applyForce:SCNVector3Make(velocity.x*speed, 0, velocity.y*speed) impulse:YES];

// if comment these lines the problem doesn't appears
node.eulerAngles = SCNVector3Make(0, angle, 0);
ship.eulerAngles = SCNVector3Make(0, angle, 0);

[node setPosition: nodePosition];
[ship setPosition: shipPosition];


Answered By - Ramy Al Zuhouri
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] how to print out bool in objective c

 September 18, 2022     boolean, iphone, objective-c, printing     No comments   

Issue

I have set a bool value for key TCshow in my NSUserDefault, I want to run a nslog test whether the key is saved or not, and i m trying to printout the bool value. here is my code but it s not working, any suggestions?

- (IBAction)acceptAction:(id)sender {
//key store to nsuserdefault
self.storedKey = [[NSUserDefaults alloc] init];
[self.storedKey setBool:YES forKey:@"TCshow"];
//trying to print out yes or not, but not working...
NSLog(@"%@", [self.storedKey boolForKey:@"TCshow"]);

}

Solution

%@ is for objects. BOOL is not an object. You should use %d.

It will print out 0 for FALSE/NO and 1 for TRUE/YES.



Answered By - Peter Warbo
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to print NSValue bytes

 September 18, 2022     cocoa, nsvalue, objective-c, printing, swift     No comments   

Issue

How does one print NSValue bytes? When using print it doesn't print all the bytes and puts '...'. E.g. {length = 128, bytes = 0x00000000 0000f03f 00000000 00000000 ... 00000000 0000f03f }

import Cocoa
import SceneKit

var identityMatrix = SCNMatrix4()

identityMatrix.m11 = 1
identityMatrix.m12 = 0
identityMatrix.m13 = 0
identityMatrix.m14 = 0
identityMatrix.m21 = 0
identityMatrix.m22 = 1
identityMatrix.m23 = 0
identityMatrix.m24 = 0
identityMatrix.m31 = 0
identityMatrix.m32 = 0
identityMatrix.m33 = 1
identityMatrix.m34 = 0
identityMatrix.m41 = 0
identityMatrix.m42 = 0
identityMatrix.m43 = 0
identityMatrix.m44 = 1

var a = [NSValue]()

a.append(NSValue(scnMatrix4:identityMatrix))

identityMatrix.m11 = 1
identityMatrix.m12 = 0
identityMatrix.m13 = 0
identityMatrix.m14 = 0
identityMatrix.m21 = 0
identityMatrix.m22 = 1
identityMatrix.m23 = 0
identityMatrix.m24 = 0
identityMatrix.m31 = 0
identityMatrix.m32 = 0
identityMatrix.m33 = 1
identityMatrix.m34 = 0
identityMatrix.m41 = 0
identityMatrix.m42 = -1.0
identityMatrix.m43 = 0
identityMatrix.m44 = 1

a.append(NSValue(scnMatrix4:identityMatrix))

print(a[0])

Solution

First of all, we can tidy this up by using an array literal, and the SCNMatrix4 initializer to get rid of all the mutability:

import Cocoa
import SceneKit

let a = [
    SCNMatrix4(
        m11: 1, m12: 0, m13: 0, m14: 0,
        m21: 0, m22: 0, m23: 0, m24: 0,
        m31: 0, m32: 0, m33: 1, m34: 0,
        m41: 0, m42: 0, m43: 0, m44: 1
    ),
    SCNMatrix4(
        m11: 1, m12:  0, m13: 0, m14: 0,
        m21: 0, m22:  1, m23: 0, m24: 0,
        m31: 0, m32:  0, m33: 1, m34: 0,
        m41: 0, m42: -1, m43: 0, m44: 1
    ),
].map(NSValue.init(scnMatrix4:))

print(a[0])

That makes the code much more sensible. We can also notice from the documentation that there's already a constant that we can use to get an identity matrix:

import Cocoa
import SceneKit

let a = [
    SCNMatrix4Identity,
    SCNMatrix4(
        m11: 1, m12:  0, m13: 0, m14: 0,
        m21: 0, m22:  1, m23: 0, m24: 0,
        m31: 0, m32:  0, m33: 1, m34: 0,
        m41: 0, m42: -1, m43: 0, m44: 1
    ),
].map(NSValue.init(scnMatrix4:))

print(a[0])

It's not clear why these matrices are wrapped in NSValue, but to display details about them (and call other methods on them), you'll need to fish the matrix back out of the NSValue box using the scnMatrix4Value API:

let sampleMatrix = a[0].scnMatrix4Value
print(sampleMatrix)

If you want to print the byte layout of these, (although it's still really not clear why you would want this, since AFAICT, NSValue and SCNMatrix4 make no promises about their memory layout), you can use the usual pointer APIs, in combination with some hex printing logic such as this:

withUnsafeBytes(of: &sampleMatrix) { sampleMatrixPointer in
    print(sampleMatrixPointer.map { String(format: "%02x", $0) }.joined(separator: ""))
}

prints:

000000000000f03f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f03f0000000000000000000000000000000000000000000000000000000000000000000000000000f03f


Answered By - Alexander
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] How to compare decimal values

 August 10, 2022     compare, decimal, ios, objective-c     No comments   

Issue


I have a problem with comparison two decimal values.
I have a text field that contains number like 0.123456 and NSNumber that contains 0.000001.
Maximum fraction digits of both is 6. Minimum - 0
I've tried to do it like that:

NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
[decimalFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[decimalFormatter setMaximumFractionDigits:6];

double sum = [[decimalFormatter numberFromString:self.summTextField.text] doubleValue];

if (self.minSum != nil) {
    if (sum < [self.minSum doubleValue]) {
        return NO;
    }
}

But i have a problem, that sometimes 0.123456 = 0,123455999... or 0,123456000000...01 For example @0.000001 doubleValue < @0.000001 doubleValue - TRUE.


How can I compare to NSNumber with a fractional part, to be sure that it will be correct?


Thanks in advance.


Solution

You can round your value, if you worried about fractional part... Something like this:

-(double)RoundNormal:(double) value :(int) digit
{
    value = round(value * pow(10, digit));
    return value / pow(10, digit);
}

And then compare it.



Answered By - Konstantin
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 4, 2022

[FIXED] How to catch C++ exception code in iOS Objective-C?

 August 04, 2022     c++, exception, ios, objective-c     No comments   

Issue

I'm new to iOS programming, now I met a problem related to catching the exception code threw from a C++ class.

    @try {
        myCPPClass myObj ; //this throws integer exception codes
    }
    @catch (...) { //I want to catch the integer value here, how ??
        NSLog(@"Exception:") ;
    }
    @finally {
    } 

I knew it maybe not a good practice coding Objective-C in exception catching style, I'd like to know how to make custom exception class for C++ classes in Objective-C ?


Solution

Rename your objective-c .m source files to have the .mm extension. They will then be compiled as objective-c++ which is fully compatible with objective-c while offering all the facilities of c++.

then you can catch c++ exceptions with the usual

try {
   ...
}
catch(std::exception& e) {
   ...
}

construct.



Answered By - Richard Hodges
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 31, 2022

[FIXED] How to cancel multiparts uploading file inbetween ios(how to cancel background thread)

 July 31, 2022     image-uploading, ios, multipartform-data, multithreading, objective-c     No comments   

Issue

hello i am using this code to upload an image to server by multiparts format. and everything working file. But according to my requirement if the image data is heavy(large) then i want to cancel the uploading in between.

My Code is

 NSString *imagePostUrl = [NSString stringWithFormat:@"%@/users/%@/profilepic",Kwebservices,[[NSUserDefaults standardUserDefaults] valueForKey:@"l_userid"]];
//
NSString *fileName = [NSString stringWithFormat:@"profilePic%ld%c%c.png", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];


AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://server.url"]];


NSDictionary *parameters = @{@"":@""};
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager setResponseSerializer:responseSerializer];
manager.securityPolicy.allowInvalidCertificates = YES;

manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

AFHTTPRequestOperation *op = [manager POST:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [formData appendPartWithFileData:imagedata name:fileName fileName:@"photo.jpg" mimeType:@"image/jpeg"];


} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);

    NSURL *imageURL = [NSURL URLWithString:imagestr1];
    imageViewProfile.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];

    [kappDelegate HideIndicator];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@ ***** %@", operation.responseString, error);

    [HelperAlert alertWithOneBtn:AlertTitle description:@"Failed to upload selected profile picture" okBtn:OkButtonTitle];

    [kappDelegate HideIndicator];

    return ;
}];
[op start];

how can i stop uploading process in middle.


Solution

You can keep a reference to the operation and call the NSOperation method cancel.

For more information on how to handle this:

  • Cancel method reference

  • Responding to the cancel command

Steps:

  1. Declare the property: @property (strong, nonatomic) AFHTTPRequestOperation *imagePostOperation;
  2. Replace the declaration of your protperty inside your code with self.imagePostOperation = [manager POST:imagePostUrl ...
  3. When you want to cancel the operation: [self.imagePostOperation cancel]
  4. In the operation succes/failure callback blocks, check [operation isCancelled] to manage that case.


Answered By - lluisgh
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 20, 2022

[FIXED] Why write 1,000,000,000 as 1000*1000*1000 in C?

 July 20, 2022     c, integer, literals, objective-c     No comments   

Issue

In code created by Apple, there is this line:

CMTimeMakeWithSeconds( newDurationSeconds, 1000*1000*1000 )

Is there any reason to express 1,000,000,000 as 1000*1000*1000?

Why not 1000^3 for that matter?


Solution

One reason to declare constants in a multiplicative way is to improve readability, while the run-time performance is not affected. Also, to indicate that the writer was thinking in a multiplicative manner about the number.

Consider this:

double memoryBytes = 1024 * 1024 * 1024;

It's clearly better than:

double memoryBytes = 1073741824;

as the latter doesn't look, at first glance, the third power of 1024.

As Amin Negm-Awad mentioned, the ^ operator is the binary XOR. Many languages lack the built-in, compile-time exponentiation operator, hence the multiplication.



Answered By - Piotr Falkowski
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 18, 2022

[FIXED] How to avoid malloc while using CGImageDestinationFinalize

 July 18, 2022     animated-gif, cgimage, gif, ios, objective-c     No comments   

Issue

I am trying to programmatically create GIF in iOS, using the following stack's question:

Create and and export an animated gif via iOS?

My code looks like this:

 // File Parameters
const void *keys[] =   { kCGImagePropertyGIFLoopCount };
const void *values[] = { (CFNumberRef) 0 };

CFDictionaryRef params          = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
const void *keys2[] =   { kCGImagePropertyGIFDictionary };
const void *values2[] = { (CFDictionaryRef) params  };

CFDictionaryRef fileProperties  = CFDictionaryCreate(NULL, keys2 , values2, 1, NULL, NULL);

// URL to the documents directory
NSURL *documentsDirectoryURL  = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
NSURL *fileURL                = [documentsDirectoryURL URLByAppendingPathComponent:fileName];

// Object that writes GIF to the specified URL
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, [arrayOfAllFrames count], NULL);
CGImageDestinationSetProperties(destination, fileProperties);

for (NSUInteger i = 0; i < [arrayOfAllFrames count]; i++) {
    @autoreleasepool {
        float delayTime = [[gifFramesDuration objectAtIndex:i] floatValue]; 
        NSDictionary *frameProperties = @{
                                          (__bridge id)kCGImagePropertyGIFDictionary: @{
                                                  (__bridge id)kCGImagePropertyGIFDelayTime: [NSNumber numberWithFloat:delayTime] // a float (not double!) in seconds, rounded to centiseconds in the GIF data
                                                  }
                                          };

        UIImage *myImage = [arrayOfAllFrames objectAtIndex:i];
        CGImageDestinationAddImage(destination, myImage.CGImage, (__bridge CFDictionaryRef)frameProperties);
    }
}
if (!CGImageDestinationFinalize(destination)) {
    NSLog(@"failed to finalize image destination");
}
CFRelease(destination);
CFRelease(fileProperties);
CFRelease(params);

However once I try to add around 240 frames to the GIF file, debugger throws the following error once the CGImageDestinationFinalize gets called:

(923,0xb0115000) malloc: *** error for object 0xd1e7204: incorrect checksum for freed object - object was probably modified after being freed.

Could you please provide me with some workaround, or with a suggestion on how to avoid malloc?


Solution

First of all, try debugging your app using Instruments. You probably will notice that the problem is caused by the method: Generatefromrgbimagewu

I have been wondering whether the cause was in my threads implementation, but it turns out, that once you have that kind of error, you should focus on resizing the Image.

Once the image had been resized, the code published above, will generate your own GIF.



Answered By - Michael
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing