vendredi 31 juillet 2015

Upload Image On server with the post method IOS

in my application i want to upload my image in jpg format to given link which content type must be multi part/form data and HTTP method is post without using any third party library. upon successful upload i will get link of uploaded image from server as a response. as i am new to IOS development. please help me in doing this Code. Thanks In advance

How to run a applescript (.scpt) programmatically in my OS X app?

I have a small applescript and I want to run it as soon as a button is pressed in my application, how do I get this done? I've made this OS X app in Objective-C.

slide animation does not work with loading of images?

I have two views in my view controller.At one time i am showing just on view & on that view i am loading some images from server.I have given an arrow to view next view on right side.When i touch arrow icon then my first view is hide & second view is shown with a slide animation.

code for slide animation

 CGFloat screenWidth=self.view.frame.size.width-68.0;
    [self.back_view setHidden:false];
    [self.front_view setHidden:true];
    [UIView animateWithDuration:0.5 animations:^{
        self.front_view.frame = CGRectOffset(self.front_view.frame, -screenWidth, 0.0);
        self.back_view.frame = CGRectOffset(self.back_view.frame, -screenWidth, 0.0);
    }];


 CGFloat screenWidth=self.view.frame.size.width-68.0;
    [self.back_view setHidden:true];
    [self.front_view setHidden:false];
    [UIView animateWithDuration:0.5 animations:^{
        self.front_view.frame = CGRectOffset(self.front_view.frame, screenWidth, 0.0);
        self.back_view.frame = CGRectOffset(self.back_view.frame, screenWidth, 0.0);
    }];

so if the images are loading from network & i try to move the view then animation does not work properly my view is hidden & second view is not shown.But if the image loading works just fine.So what could be issue for which slide does not work properly?

App sharing link ios before making it public on apple store

I am working on a app which contain the functionality of sharing the app link via UIActivityController. Here its will very first version of app. So I don't know the URL of the app. Please provide me any way to get it before making it public, So I can integrate the sharing functionality in the app.

Thanks

master detail open programatically ios

This is doing my head in... (iPhone only, it works on iPad) Take the template "master detail", in the detail view you see the left UINavigationBarItem which triggers the step back to the master.

When you replace that NavigationBarItem, it loses the target and action, fair enough.

How to trigger this manually, i've tried all ... [navBarButtonOpenMenu addTarget:self.splitViewController action:@selector(_triggerDisplayModeAction:) forControlEvents:UIControlEventTouchUpInside]; does nothing

fetching the target and selector from the current UINavBar left button doesn't work (reference will be lost i would imaging)...

I would just like to manually trigger open and close with custom button (close bing back to current detailviewcontroller)

How to fix or disbale orientation of iOS device for few ViewController?

I have an app which is having 9-10 screens.I have embed navigation controller to my view controller.So i have few view controller for which i want set only portrait orientation it means on rotating the device view controller should not rotate to landscape mode.I have tried following solutions?

first:

   NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
   [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

but screen still rotates to landscape.

Second: I created custom view controller class as PortraitViewController & add below code in PortraitViewController.m

@interface PortraitViewController ()

@end

@implementation PortraitViewController

- (BOOL)shouldAutorotate
{

    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    //Here check class name and then return type of orientation
    return UIInterfaceOrientationMaskPortrait;
}

@end

After that i implemented PortraitViewController.h as base class

#import <UIKit/UIKit.h>
#import "PortraitViewController.h"
@interface Login : PortraitViewController
@end

does not work at all still allow view controller to rotate in landscape mode

Is there any other solution i am using iOS 8 & don't want viewcontroller to rotate in landscape mode?

Latest Google Plus iOS SDK 1.7.1 not supporting architecture x86_64

I have the latest Google Plus iOS SDK managed by cocoapods in my project.

pod 'google-plus-ios-sdk' ~> '1.7.1' #(Also tried 1.5.1)

Simple code as:

#import <GooglePlus/GooglePlus.h>
[GPPSignIn sharedInstance].clientID = kClientID; 

I get this error:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_GPPSignIn", referenced from:
      objc-class-ref in GooglePlusManager.o
  "_OBJC_CLASS_$_GPPURLHandler", referenced from:
      objc-class-ref in GooglePlusManager.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have $(inherited) and -ObjC in my Other Linker Flags. Does Google Plus iOS SDK not support x84_64 architecture at all? How do I fix this issue? Thanks

Not able to add UIBarButton programatically to UINavigationBar ( UITabbarController)

I have a UITabbarController and connected to 5 UIViewController, and i have added UIBarButton to UINavigationbar in ViewController1.

But When i run that application am not able to see the UIBarButton in navigationbar, i can see only one plain navigationbar.

This is the code to update UINavigationBar.

UIImage *myImage = [UIImage imageNamed:@"filter.png"];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setImage:myImage forState:UIControlStateNormal];
myButton.showsTouchWhenHighlighted = YES;
myButton.frame = CGRectMake(0.0, 0.0,25,25);
[myButton addTarget:self action:@selector(refreshSection) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];
self.navigationItem.leftBarButtonItem = rightButton;

This was working without UITabbarController, but when i added UITabbarController to my storyboard its not working pls help me..

Getting CFReadStreamRef and CFWriteStreamRef from CFSocket

-(void) createSocket
{
    int sockfd;
    struct sockaddr_in servaddr;
    char sendline[] = "hello world";

    char addr[] = “10.0.0.1";


    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(addr);
    servaddr.sin_port=htons(5527);

    sendto(sockfd,sendline,strlen(sendline),0,
               (struct sockaddr *)&servaddr,sizeof(servaddr));

    // Create CFSocket
    const CFSocketContext   context = { 0, (__bridge void *) (self), NULL, NULL, NULL };
    CFSocketRef _cfSocket;
    _cfSocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketReadCallBack, kCFSocketReadCallBack, &context);

}

Hi,

I am new to objective c. As a part of a simple project I needed to build a UDP based client in objective c.

I have managed to create C based socket and get a CFSocket reference from it.

The place where I am stuck is:

Get a CFReadStreamRef and CFWriteStreamRef for the CFSocket that I have created.

is there a way that I can do that? I read the documentation for CFStream at apple but I couldn’t figure out much there. Any suggestions would be great.

Thanks

Why does Xcode copy my project file within project file?

Say I have an Xcode project in a directory Y. Xcode has put the directory Y inside Y inside Y and inside Y is Y. It seems to be never ending. Why has it done this and is there anything I can do to rectify the problem? I am working with Xcode beta, and it is doing a number on my build, clean, and run times.

Linker error when try to call ObjC method from C

Actually, I'm a Unity developer and I know nothing about XCode and Objective C. But I have to use ObjC library for some integration and call this function from Unity. So I import that library to created XCode project and write some wrapper code between Unity and XCode. When I try to call empty function, it works for me. But when i try to write ObjC method in C file it causes linker error and I have no idea what's wrong with it. So, here's the deal:

In Unity MonoBehaviour.cs:

[DllImport("__Internal")]
public static extern void startWithAPIKey(string apiKey);
...
startWithAPIKey(apiKey);

In XCode Wrapper.h:

@interface IOSYandexMetricaWrapper : NSObject
@end

In XCode Wrapper.m:

#import "YandexMobileMetrica.h" //library header
#import "IOSYandexMetricaWrapper.h"

void startWithAPIKey(char *apiKey) {
    //method that i want to call
    [YMMYandexMetrica startWithAPIKey:(NSString *)apiKey];
}

So it compiles, but linker says something like this: Undefined symbols for architecture armv7: "_OBJC_CLASS_$_YMMYandexMetrica", referenced from: objc-class-ref in IOSYandexMetricaWrapper.o

Someone can help me with my problem?

How to fix orientation of few controller in portrait mode only?

I am developing an application in which i am having one Navigation Controller which further has few ViewController as child.Now for few ViewController i want keep the orientation for portrait mode.How can i do that ?

EDIT:

I created custom view controller class as PortraitViewController & add below code in PortraitViewController.m

@interface PortraitViewController ()

@end

@implementation PortraitViewController

- (BOOL)shouldAutorotate
{

    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    //Here check class name and then return type of orientation
    return UIInterfaceOrientationMaskPortrait;
}

@end

After that i implemented PortraitViewController.h as base class

#import <UIKit/UIKit.h>
#import "PortraitViewController.h"
@interface Login : PortraitViewController
@end

But still now working if rotate the device into landscape mode.

Will learning Objective-C before C help you pick up C later on?

I'm a novice programmer looking to build my own iOS app. I'm hearing a lot of mixed responses on how it may or may not be necessary to learn C before taking on Objective-C.

I'm leaning towards learning Objective-C first considering I can always look back into the C (I'm using Big Nerd Ranch Guide for Objective-C) for some concepts like structs, arrays, etc.

I'm open to hearing any advice on what any of you may think!

Can i write a part of an iOS app in python?

Note: There is a duplicate question, however I believe the answers may be outdated as a lot has changed since 2012 for iOS development.

I know that when programming for iOS you can bind to C/C++ from Objective-C. Can you do the same with Python, and if so, what is the best way to go about doing it? I would ideally like to write most of my app including the GUI in Objective-C and then write some python code to analyze some audio data using something like this. The only library I have found that may be able to this is PyObjC, but I read that this library is not well-supported for iOS. Is this is best option?

Thank you very much.

UITextField "content size" property

Is there a way to make the right side of a UITextField's content "end sooner" like in this graphic:

enter image description here

I'm using the following to give the content text some left padding, but can't figure out an easy solution to reduce the available content size on the right size: self.textfield.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 0);

I'd rather not subclass UITextField but I'm fine doing so if need be.

Unwrapping NSMutableArray from Database

How do I unwrap a NSMutableArray that has been stored in a database? This is what I receive if I do NSLog(@"%@",webData);

Food items: (
    "Gold Chopsticks Prawns",
    "Gold Chopsticks Scallops",
    "General Tsou's Chicken"
)

I'm trying to add those 3 items to an NSMutableArray so I can access them like "objectatIndex:1" should return "Gold Chopsticks Scallops".

Thank you

Adding WatchKit cause Linker error - entry point (_main) undermine for arch arm64

I get this linker error for the WatchKit Extension target after adding watch kit to an existing iOS project. I've not really any ideas where to start in the hunt for the solution to this problem, and can't see any similar threads like it in the forums. My iOS app is a typical ObjC app running on iPhone6+ (for debug). The target architecture is "standard architectures (armv7, arm64) Any ideas?? I am at a loss. Thanks Rob.

Copying and Referencing of NSObjects iOS

So for a while I have been working on this app - in which contains a folder-like structure of objects which have properties of arrays that can contain the same type of object, which in turn can contain more of this object, etc. These objects are called groups. In a shared data class I have a mater group object called mainGroup, and a property of my data class called selectedGroup to facilitate the display of data. These group objects can be modified, so for a considerable chunk of time I tried to develop a solution for getting the path through all of the arrays to the desired object, all the while having no clue about copying and that assigning one array equal to the other does not create a deep copy, just some kind of reference. The code was logically sound, but in it after a while I noticed that deleting things in the selectedGroup’s array property had the same effect on the actual master copy, which did some wonky things to my app.

I did some googling and figured out that I was not actually creating a whole new array, just referencing it some how. I’m still confused on this next part though. I thought that setting one array equal to the other would have the same effect as calling copy on it - and when I replace or delete objects in one array the other is affected. So what exactly is the compiler doing when you set two arrays equal to each other? Shouldn’t it just populate the new array with the pointers to the objects in the old array, not just reference the array itself? And how come that when doing this same operation with objects such as NSStrings you do not see the same effect? Lastly, what other objects have this same behavior as the NSArrays?

UIImageView showing content with severe delay

This is really a mystery for me (iOS 8, Xcode 6.x, Storyboard):

I'm presenting one view controller (VC) modally, overlaying on the VC presenting it.

On the VC being presented, there's a static image with pdf assets. When the VC is loaded, the image doesn't show up, then after like 20 seconds, it shows up.

What could have gone wrong? I have image cache setup inside this VC's code, so I removed that, result the same. I also tried to switch the asset to a png image, still the same. I'm really confused now, any comments?

How do I prevent UITableViewCell from changing after edit?

In the image below, I swipe the cell to the left to reveal actions. Once the action is done, the cell adjusts back to normal... but not quite because the right side alignment is off. I'd like to get some ideas as to how to correct that behavior.

Here is a screenshot of it with the view debugger to outline the objects. enter image description here

As you can see, the left hand side is still perfectly aligned. But the right hand side's trailing constraint is either disregarded (w/o telling me a constraint was broken) or some other thing is happening that I don't understand. The position of the button on the right varies from far off to only slightly off.

My actions are setup using tableView: editActionsForRowAtIndexPath:. Now, I get this scenario even if no action is taken and the user selects the part of the cell that isn't an action. However, within the actions I am also executing this line:

I tried to capture the value of the trailing constraint within the action, although I don't know if I am doing this correctly because the values came out the same.

FavoriteTableViewCell *cell = (FavoriteTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Trailing Constraint before: %f)",cell.dragTrailingConstant.constant);
[self.tableView setEditing:NO animated:NO];
NSLog(@"Trailing Constraint  after: %f)",cell.dragTrailingConstant.constant);

Trailing Constraint before: -4.000000

Trailing Constraint after: -4.000000

The trailing constraint is: Superview.Trailing.Margin Equal DragButton.Trailing. Constant -4. Priority 1000. Multiplier 1.

Making NSImage Out of NSBezierPath

I have an NSBezierPath object. Its path can make a shape like a triangle, octagon or whatever. I could create an NSImage object by clipping a color rectangle with this path. But that's not what I want to do because I want to add a stroke to the path. For now, I have the following code in creating a path making some shape.

[[NSColor greenColor] set];
NSBezierPath *path = [NSBezierPath bezierPath];
makeBezierPath *makebezier = [[makeBezierPath alloc] init]; // NSBezierPath subclass
path = [makebezier makePath:4:1:NSMakeRect(0,0,200.0f,200.0f)];
[path fill];
[path setLineWidth:10.0f];
[path closePath];
[[NSColor greenColor] set];
[path stroke];

I would like to make an NSImage object right out of this path. Is that possible? The other reference I have found so far is this one. I could display the shape with an NSView subclass and then convert that view into NSImage, which is not what I want to do, either.

Thank you for your help.

Best AutoLayout Library for Objective C iOS?

What's the best autolayout library to use for iOS when developing in Objective C?

UIImageView+AFNetworking setImageWithURL causing memory leaks

My task is downloading captcha image to show in the UITableViewCell.
So I have a IBOutlet named captchaImageView and use UIImageView+AFNetworking to implement it.
The key codes as follows.

@property (weak, nonatomic) IBOutlet UIImageView *captchaImageView;
/**/
- (void)viewDidLoad {
    [super viewDidLoad];

    _captchaImageView.userInteractionEnabled = YES;
    [_captchaImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshCaptcha)]];
    [self refreshCaptcha];
}
- (void)refreshCaptcha {
    [_captchaImageView setHidden:YES];
    [_captchaImageIndicator startAnimating];

    __weak UIImageView *weakImageView = self.captchaImageView;
    [weakImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:kCaptchaImageRequestUrl]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:kRefreshCaptchaTimeoutInterval]
                         placeholderImage:[UIImage imageNamed:@"RefreshCaptcha"]
                                  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                      __strong UIImageView* strongImageView = weakImageView;
                                      [strongImageView setHidden:NO];
                                      [strongImageView setImage:image];
                                  }
                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                                  }];
}

However, it leads memory leaks. The below image is captured by Instruments leaks tool. enter image description here After rewrite the refreshCaptcha method, the leak also occured.

- (void)refreshCaptcha {
    [_captchaImageView setHidden:YES];

    __weak UIImageView *weakImageView = self.captchaImageView;
    [weakImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:kCaptchaImageRequestUrl]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:kRefreshCaptchaTimeoutInterval]
                         placeholderImage:[UIImage imageNamed:@"RefreshCaptcha"]
                                  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                  }
                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                                  }];
}

I can not understand that even the success and failure blocks are empty how the leaks can reach? Whether it is my incorrect use or UIImageView+AFNetworking has a bug about this?

Is it possible to use custom view for SKCalloutView

Like the name says it, is it possible to make a custom UIView, with elements such as Label and Button, and use it as a CalloutView?

What I read through the documentation so far doesn't implicates that it is possible.

Changing left and right button is possible, together with adding custom UIIMageView for an arrow, But Couldn't figure out if Customising entire view is actually possible.

How to get and load nested JSON values into Tableview Objective c?

Below I have posted my nested JSON response. I want to get all the keys and key values to load into one tableview like below UI. Please help me!

My JSON

response : {

     ANI =  { 
             name = "anisharmu";
             age  = "10";
     };

     ROC =  { 
             name = "rockins";
             age  = "20";   
     };
}

MY UI Tableview

|------------------------|
  ANI anisharmu - 10
|------------------------|

My Code

 NSError *error;
 jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
 // get keys from response dictionary
 NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[jsonDictionary[@"response"] allKeys]];

 // sort as asending order
 NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: YES];
 key =  (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];

 // access inner data from dictonary
 for (NSString * obj in key) {

            NSLog(@"%@",jsonDictionary[@"response"][obj][@"name"]);

 }

Snapchat friends through address book

How does snapchat allow you to access and add friends through your address book? I understand that you can pull information/phone numbers from your contact list, but how does snapchat actually get your phone number, since that operation is prohibited by objective-c? It seems necessary in order to be able to store a username with a particular phone number.

How to calculate route using viaPoints array

If I have a route calculated from point A to point B using the following code:

[SKRoutingService sharedInstance].routingDelegate = self;
[SKRoutingService sharedInstance].navigationDelegate = self;
[SKRoutingService sharedInstance].mapView = _mapView;
SKRouteSettings* route = [[SKRouteSettings alloc]init];
route.startCoordinate=CLLocationCoordinate2DMake([Constants shared].location.x, [Constants shared].location.y);
route.destinationCoordinate=CLLocationCoordinate2DMake([Constants shared].destination.x, [Constants shared].destination.y);
route.shouldBeRendered = YES;
SKNavigationSettings* navSettings = [SKNavigationSettings navigationSettings];
navSettings.navigationType=SKNavigationTypeSimulation;
navSettings.distanceFormat=SKDistanceFormatMilesFeet;

[SKRoutingService sharedInstance].mapView.settings.displayMode = SKMapDisplayMode2D;
[[SKRoutingService sharedInstance] calculateRoute:route];

And the above is all fine. Route will be calculated and display with no problem. But how do I add a viaPoint to the already calculated route? Do I need to clear the already created one and calculate new one, or somehow recalculate the existing one with another point added.

And another question, how do I properly create a SKViaRoute object?

UIAttachmentBehavior not working for pong AI that can lose

So I am trying to implement a basic pong AI that is decent, but can be beaten. I have tried [UIView animateWithDuration...] UISnapBehavior and UIAttachmentBehavior.

animateWithDuration does not update the collision detection properly so i get invisible walls

UISnapBehavior is still too fast, and does not respond to friction or resistance to slow down

UIAttachmentBehavior seems to be my best bet, because it works with my collision behavior like Snap but is more flexible. However, I cannot get it to work. Open to all suggestions, here's the code:

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

[self startGame];
}

basic method that just gets everything going

- (void)startGame {
[self createBall];
[self createPlayerPaddle];
[self createAIPaddle];
[self createCollisions];

// Remove rotation
self.paddleDynamicProperties = [[UIDynamicItemBehavior alloc] initWithItems:@[self.paddleView, self.paddleViewAI]];
self.paddleDynamicProperties.allowsRotation = NO;

//make heavy
self.paddleDynamicProperties.density = 1000.0f;

//make slow
self.paddleDynamicProperties.friction = 1000;

[self.animator addBehavior:self.paddleDynamicProperties];
}

we'll look at collisions and the paddleViewAI

- (void)createCollisions {
self.collider = [[UICollisionBehavior alloc] initWithItems:@[self.ballView, self.paddleView, self.paddleViewAI]];
//self.collider.collisionDelegate = self.paddleView;
self.collider.collisionMode = UICollisionBehaviorModeEverything;
[self.collider addBoundaryWithIdentifier:@"left" fromPoint:CGPointMake(0, 0) toPoint:CGPointMake(0, self.view.frame.size.height)];
[self.collider addBoundaryWithIdentifier:@"right" fromPoint:CGPointMake(self.view.frame.size.width, 0) toPoint:CGPointMake(self.view.frame.size.width, self.view.frame.size.height)];
[self.animator addBehavior:self.collider];
}
- (void)createAIPaddle {
CGRect paddleRect = CGRectMake((self.view.frame.size.width / 2), 30, 100, 10);
self.paddleViewAI = [[UIView alloc] initWithFrame:paddleRect];
self.paddleViewAI.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.paddleViewAI];

//make AI work
//track location of ball
[self addObserver:self forKeyPath:@"self.ballView.center" options:NSKeyValueObservingOptionNew context:nil];
}

and finally where i respond to the changes of the balls position as it moves along

-(void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString *,id> *)change context:(nullable void *)context {
if ([keyPath isEqualToString:@"self.ballView.center"]) {

    if (!CGRectContainsRect(self.view.frame, self.ballView.frame)) {
        [self createBall];
        [self createCollisions];
    }

    CGPoint location = self.ballView.center;

    //paddle respond to location of ball

    if (self.dxAI == 0) {
        self.dxAI = location.x - self.paddleViewAI.center.x;
    }
    //create offsets
    CGPoint newLocation = CGPointMake(location.x - self.dxAI, self.paddleViewAI.center.y);
    CGRect newRect = CGRectMake(newLocation.x - (self.paddleViewAI.frame.size.width / 2), self.paddleViewAI.frame.origin.y, self.paddleViewAI.frame.size.width, self.paddleViewAI.frame.size.height);


    //keep paddle inside view
    if (CGRectContainsRect(self.view.frame, newRect)) {
        //apply offsets

        if (self.attach != nil) {
            [self.animator removeBehavior:self.attach];
        }
        self.attach = [[UIAttachmentBehavior alloc] initWithItem:self.paddleViewAI attachedToAnchor:self.paddleViewAI.center];
        // the plan was adjust the frequency to affect speed so AI will only be able to keep up sometimes
        self.attach.frequency = 20;
        self.attach.damping = 1;
        [self.attach setAnchorPoint:newLocation];
        [self.animator addBehavior:self.attach];

    }
    //update animations
    [self.animator updateItemUsingCurrentState:self.paddleViewAI];
    }
}

I could use UISnap, UIAttach, or the UIView animateWithDuration in this last method but as I mentioned none quite works. I'm open to any suggestion, or just to get the UIAttach to at least work would be lovely.

Parsing HTML in Objective C using Hpple

Below is the my HTML code(actually little part of it) that I try to parse through in Objective-C;

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ift.tt/nYkKzf">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title>Random string here</title>
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1347.57">
  <style type="text/css">
    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000}
    p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times; color: #0000ee; -webkit-text-stroke: #0000ee}
    p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; text-align: right; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000}
    p.p4 {margin: 0.0px 0.0px 12.0px 0.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000}
    p.p5 {margin: 0.0px 0.0px 12.0px 0.0px; font: 11.0px Times; color: #000000; -webkit-text-stroke: #000000; background-color: #ffffff}
    p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}
    p.p7 {margin: 0.0px 0.0px 12.0px 0.0px; font: 12.0px Times; color: #000000; -webkit-text-stroke: #000000; min-height: 14.0px}
    p.p8 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times; color: #ffffff; -webkit-text-stroke: #ffffff}
    td.td10 {width: 54.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td11 {width: 43.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td12 {width: 48.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td13 {width: 52.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td14 {width: 38.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td15 {width: 55.0px; background-color: #425165; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td43 {width: 55.0px; background-color: #f3f3f3; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td48 {width: 49.0px; background-color: #f3f3f3; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
  </style>
</head>
<body>
<table width="787.0" cellspacing="0" cellpadding="0" class="t1">
  <tbody>
    <tr>
      <td valign="top" class="td1">
        <p class="p1"><span class="s1"> </span></p>
        <table cellspacing="0" cellpadding="0">
          <tbody>
            <tr>
              <td valign="middle" class="td2">
                <p class="p2"><span class="s1"><a href="http://ift.tt/1H3Fqk4"><span class="s2"></span></a></span></p>
              </td>
              <td valign="middle" class="td3">
                <p class="p3"><span class="s1">2014-2015 Summer School<span class="Apple-converted-space"> </span></span></p>
              </td>
              <td valign="middle" class="td4">
                <p class="p1"><span class="s1"> </span></p>
              </td>
            </tr>
          </tbody>
        </table>
        <table cellspacing="0" cellpadding="0">
          <tbody>
            <tr>
              <td valign="top" class="td5">
                <p class="p1"><span class="s1"> </span></p>
              </td>
              <td valign="top" class="td6">
                <p class="p4"><span class="s1"><b>random string /COURSE CODE :</b></span></p>
                <p class="p5"><span class="s1">some string here/Select</span></p>
                <p class="p5"><span class="s1">string1<span class="Apple-converted-space"> </span></span></p>
                <p class="p5"><span class="s1">string2<span class="Apple-converted-space"> </span></span></p>
                <p class="p5"><span class="s1">string3<span class="Apple-converted-space"> </span></span></p>
                <p class="p5"><span class="s1">string4<span class="Apple-converted-space"> </span></span></p>

Assume that i want to get the strings that are at end of the code (string1, string2, string3 and string4);

To reach them when I write my path like that;

NSString *myXpath = @"//p[@class='p5']";

Simply its not working. My searchWithXPathQuery function returns nothing. I tried to change myXpath like "//p[@class='p5']/span[@class='s1']" but still there is no result. Part of my code after creating xpath;

NSArray *tutorialNodes = [tutorialsParser searchWithXPathQuery:myXpath];

        for(TFHppleElement *element in tutorialNodes){

            NSLog(@"Content: %@", [element content]);
        }

How can I write these strings to my console ?

iOS UiAutomation - Predicate with Single Quote in String

I'm currently using iOS UIAutomation and identifying elements with a string generated from an external database that is populated with dynamic data. But iOS uiautomation throws a parser error when the string predicate contains a single quote.

Example: "UIATarget.localTarget().frontMostApp().mainWindow().collectionViews().firstWithPredicate(\"ANY visibleCells.name CONTAINS '" + title + "'")"

Note that if title = "Todds Apartment" this locator works fine. But if the string contains a single quote it throws the parser error. So for example if title = "Todd's Apartment" this wouldn't work.

Is there a way for the predicate evaluation within single quotes to contain a single quote?

iOS - Previous screen flashing when coming from background

This is my situation: I push a ViewController that is in landscape mode, then go to the home screen. When I go back in the app, the previous views in the back stack flash for just a moment before going to my ViewController. This doesn't happen for portrait ViewControllers.

Has anyone seen this before or know of a workaround? Thanks!

For the record, I am simply pushing the ViewController via:

self.navigationController!.pushViewController(viewController, animated: true);

and then forcing the view into landscape mode, not sure if that's relevant.

How to suppress header file warnings from an Xcode project

When I build UnzipKit in Xcode 7 beta 4, I'm getting a compiler warning in MiniZip's ioapi.h file. For example:

.../ioapi.h:22:9: warning: macro name is a reserved identifier [-Wreserved-id-macro]
#define _ZLIBIOAPI64_H

ioapi.c has many of its own warnings, so I compile it with -Wno-everything like so:

Compile Sources build phase

However, there is no "Compiler Flags" setting available for the headers:

Headers build phase

How can I silence the warning without modifying the source file? I'd rather not modify it, as it's an external dependency. I also don't want to turn it on for the whole project, because it's a useful warning for my own code.

iOS Constraints Way off On Device Only

I have an iPad app with a nice layout that looks fine in every version of the iPad simulator (iPad 2, iPad Air, iPad Retina). However when I sync it to my actual iPad Air 2, the constraints of some assets are way off.

I've tried uninstalling the app, restarting the iPad, clean builds, etc. Nothing seems to work.

Any debugging suggestions?

Opening Safari URL in my app

Is it possible, using Objective-C, to register an action for Safari URLs similar to the "Open In..." dialogue that allows users to open the page in my app? Something like this:

enter image description here

Rounding edge on UITextField

I have 3 UITextFields with border style none. I want to add borders in code. The effect I want to achieve is to have rounded top corners on first UITextField and to have rounded bottom corners on third text field. Code I am using for rounding edges is here Round top corners of a UIView and add border

But i get this - no right edge and corners are not rounded:

http://ift.tt/1Izbt0O

Note: I've set all constraints, that is not a problem. If i use UITextBorderStyleLine right edge is not rounded again.

Please help.

Special characters showing bold in UILabel

I have a UILabel that I'm trying to show some spanish text in however the special characters are showing up bold?? The text is going in a UITableViewCellStyleSubtitle cell.

Here is what it's looking like:

enter image description here

UIViewController view is chopping off

I am new to iOS and ObjectiveC and trying to add a viewcontroller to my existing program. It is showing partly in iPhone 6..any suggestions to reset the view to display all?

Send local notification when download completes through NSURLSession / NSURLSessionDownloadTask

I am using NSURLSessionDownloadTask objects on an NSURLSession to allow users to download documents while the app is in the background / device locked. I also want to inform the user that individual downloads have finished through a local notification.

To that end, I am triggering a local notification in the -URLSession:downloadTask:didFinishDownloadingToURL: download task delegate method, however I am wondering if there might be a better place to add the code triggering a notification, since the way Apple explains it, the download task will be passed to the system, and from that I am deriving that those delegates will not be called anymore on the download task's delegate once (or shortly after) the app is backgrounded.

My question: What is the best place to add the code for triggering the local notifications? Has anybody had any previous experience in adding this sort of a functionality to their application?

Cache-Control: max-age does not make AFNetworking cache the response

On the server side, I'm setting Cache-Control: max-age=14400.

From my iOS client, I'm setting up a shared instance of AFHTTPSessionManager like follows:

+ (TKClient *)sharedInstance {
static TKClient *instance = nil;
static dispatch_once_t token;

dispatch_once(&token, ^ {
    instance = [[TKClient alloc] initWithBaseURL:[NSURL URLWithString:kTKBaseUrl]];
    [instance setRequestSerializer:[AFJSONRequestSerializer serializer]];
});

return instance;

And making my API calls like this:

- (void)listingsWithParams:(NSDictionary *)params completion:(void (^)(NSMutableArray *listings, NSError *error))completion {
[self GET:@"api/listings" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
    // success here
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    // error here
}];

I have verified that the Cache-Control header is being returned properly from the server side for this listings call. However, the call goes to the server every time, and it's clearly not being cached. Any idea what the problem could be?

Do I need to configure something else on the iOS side, or change the Cache-Control headers some way? Thanks!

Saving TextView contents in TableView

I am making a to-do list app and I have a tableview with custom cells in it. The custom cells only have a textview where the user can input their "tasks". Also, the user can add rows for more tasks and delete rows if he/she has completed that task on the list. However if the app is closed the tableview is reset obviously, and the user losses everything he/she has written in the cells before. This way, the app is pretty much useless.

My question is: How could I preserve the text in each cell's TextView even after the app was closed?

EDIT: I managed to save the data in NSUserDefaults by iterating through every cell's textview and getting their text property. However the problem is that if I load the data on startup into an array and populate the cell's textviews from that array in cellForRowAtIndexPath the text in textviews are reset(to the data that was loaded on startup) whenever the user scrolls the tableview as cellForRowAtIndexPath is called again.

So my question is now: How could I overcome this issue? I would only need to populate the tableView on startup not every time cellForRowAtIndexPath is called.

My code:

I wrote a separate method for saving the contents of the cells (notes is just an empty mutable array).

-(void)saveNotes{
   NSArray *cells = [self.tableView visibleCells];
    [notes removeAllObjects];

    for (TableViewCell *cell in cells)
    {
        [notes addObject:cell.textView.text];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:notes forKey:@"notes"];
        [userDefaults synchronize];
        NSLog(@"notes saved!");
    }
}

Than in viewDidLoad I set the tableview's dataSource array to be the one that is stored in NSUserDefaults:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if([userDefaults objectForKey:@"notes"]){
        dataSource = [[userDefaults objectForKey:@"notes"] mutableCopy];
        NSLog(@"Notes loaded");
    }
    else{
        dataSource = [[NSMutableArray alloc]initWithObjects:@"", nil];
        NSLog(@"Nothing found! :(");
    }

After that, in cellForRowAtIndexPath I set the textviews of all the cells to show the text thats was loaded in viewDidLoad:

cell.textView.text = [dataSource objectAtIndex[indexPath row]];

Core Data update locations for positions in background cause blocking UI

I am using 3 Managed Object Contexts Architecture (creating temporaryContext for background which parent is managedObjectContext - UI, and which has parent writerObjectContext which should write to database in background) and I have a problem with blocking UI when I updating objects. Example would be best. So I have thousands of points in my database and I am using NSFetchedResultsController with tableView for getting them. Here is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    temporaryContext.parentContext = [[CoreDataManager manager] managedObjectContext];
    temporaryContext.undoManager = nil;

    ...
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PositionCellIdentifier forIndexPath:indexPath];
    [self configureCell:(PanelPositionCell *)cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(PanelPositionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // Fetch Record
    NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
    OpenPositionCD *position = (OpenPositionCD *)record;

    // Update Cell
    [cell setValuesByOpenPositionCD:position];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self checkAddress:position];
    });
}

- (void)checkAddress:(OpenPositionCD *)openPosition {
    if (openPosition.latitude == 0 && openPosition.longitude == 0) {
        return;
    }

    if ([openPosition hasAddress]) {
        return;
    }

    CLLocation *location = [[CLLocation alloc]initWithLatitude:[openPosition.latitude doubleValue] longitude:[openPosition.longitude doubleValue]];
    [[LocationManager manager] getPlacemarksForLocation:location withCompletion:^(NSArray *placemarks, NSError *error) {
        if (!error) {
                openPosition.address = placemarks[0];
                            NSError *error = nil;
                if (![temporaryContext save:&error]) {
                    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                }
        }
    }];
}

When I am scrolling to cells which don't have addresses the UI is freeze often which depends on how fast I am scrolling. So how can I fix it? I was trying with/without dispatch_async and with/without temporaryContext performBlock but looks nothing can help me. So thanks for any help.

I am adding initializing of contexts in CoreDataManager but I hope it's allright:

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    _managedObjectContext.parentContext = [self writerManagedObjectContext];

    return _managedObjectContext;
}

// Writer context for database
- (NSManagedObjectContext *)writerManagedObjectContext{
    if (_writerManagedObjectContext != nil) {
        return _writerManagedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _writerManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [_writerManagedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _writerManagedObjectContext;
}

NSString substringWithRange returns incorrect substring

I'm working on an OS X app, running XCode 6.4 and Yosemite. Distilling the problem down to a couple lines of code, I'm using substringWithRange to extract a substring and getting a string that's 18 characters long, but I was expecting a string with 26 characters. What am I doing wrong?

//              12345678901234567890123456789
NSString *s = @"ClientÅåÄäÖöÅåÆæØø_Example #2";
NSRange range = NSMakeRange(0, 26);
NSString *result = [s substringWithRange:range];
//              12345678901234567890123456
//              ClientÅåÄäÖöÅåÆæØø

Convert swift arrays into JSON object

I have two arrays :

let value = [41, 42, 45] ...
let date = [NSDate1, NSDate2, NSDate3] ...

I need to save the data as a json object onto our mongodb on the server. I tested with a sample object formatted as below and it worked as expected. How can I reformat my arrays into this format efficiently in swift/objective c?

let jsonObject = [
["date" : "2014/01/01", "value" : "41"],
["date" : "2014/01/02", "value" : "42"],
["date" : "2014/01/03", "value" : "45"]]

Any help would be very much appreciated ! Thank you !

Determine the Device Orientation and its resulting Angle on one Dimension?

I have the following setup:

enter image description here

An iPhone lies with the display to the ceiling on a table (alpha = 0 degrees). When the iPhone is moved upwards like shown in the image above the alpha angle increases.

How do I compute the value of the alpha angle without taking care of any other axes which could change. I am only interested in this one axis.

How do I get the correct alpha angle the iPhone has when lifting up from the table? How do I get notified when the value of alpha changes?

What OS X events can I access programatically from swift?

I'd like to find both current running programs (or at least program in the foreground) programmatically - and also key events on OS X.

I found inter-application communication guidelines, but they don't seem to say I can find out what applications are running.

I've found key events, but it seems to imply that the current task in the forefront is the one that gets the key events and only if it doesn't handle them does it go up to event chain. I'd like to programmatically intercept them.

Seems dubious, I know. I'm trying to use key events along with screen captures to try to best learn text on the screen - it's for research.

I'm using swift, but I understand that an obj-c example is pretty helpful since they all use the same libraries.

Could not find add listener in PubNub in swift

I am using Xcode 6.4 and trying to integrate the pubnub group chat functionality in my app. I followed this tutorial

http://ift.tt/1JA4JkO

I was able to do everything smoothly. But there was an error in the code. While writing this piece of code as given in the tutorial by pubnub I got this compilation error. enter image description here

Is this method not available or I am doing anything wrong?

I have used the latest Pubnub sdk as stated in the blog using cocoapods. What do I have to do in order to correct this. Any help will be appreciated. Thanks

Capturing and using CKQueryCursor results using blocks?

HELP! I don't understand blocks in objective C. Here is my code.

-(void)loadStudentControls1n2Picker
{
    postCursor = nil ;
    [self getStudent];
}

-(void)getStudent
{
    __block CKQueryCursor *cursorCursor = nil;
if (postCursor == nil ) {
    CKDatabase *publicDatabase = [[CKContainer containerWithIdentifier:@"blah.com"] publicCloudDatabase];
    NSPredicate *predicatex = [NSPredicate predicateWithFormat:@"iBeaconConfig = %@", iBeaconsConfirmed.giReferenceID];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:@"SingleBeaconsDB" predicate:predicatex];

    CKQueryOperation *queryOp =[[CKQueryOperation alloc] initWithQuery:query];
    queryOp.desiredKeys = @[@"record.recordID.recordName",@"Owner",@"iBeaconMajor",@"iBeaconMinor",@"OwnerID"];
    queryOp.resultsLimit = 4;

    queryOp.recordFetchedBlock = ^(CKRecord *results)
    {
        if (results[@"Owner"] != nil) {
            [globalPickerConfirmed addRecord:results[@"Owner"]:results.recordID.recordName];
        }
        [iBeaconSingleConfirmed addObject:results];
    };

    queryOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *operationError)
    {
        AAPLPostManagerErrorResponse error = [self handleError:operationError];
        NSLog(@"in block error & cursor %ld %@",(long)error,cursor);
        cursorCursor = [CKQueryCursor alloc];
        cursorCursor = cursor;
        postCursor = cursorCursor;
        NSLog(@"queryOp  postCursor %@",postCursor);
        [self.delegate performSelectorOnMainThread:@selector(refreshPicker:)  withObject:@"Teacher" waitUntilDone:YES];
    };
    [publicDatabase addOperation:queryOp];
} else {
    CKDatabase *publicDatabase = [[CKContainer containerWithIdentifier:@"blah.com"] publicCloudDatabase];
    CKQueryOperation *cursorOp = [[CKQueryOperation alloc] initWithCursor:postCursor];
    cursorOp.desiredKeys = @[@"record.recordID.recordName",@"Owner",@"iBeaconMajor",@"iBeaconMinor",@"OwnerID"];
    cursorOp.resultsLimit = 4;

    cursorOp.recordFetchedBlock = ^(CKRecord *results)
    {
        if (results[@"Owner"] != nil) {
            [globalPickerConfirmed addRecord:results[@"Owner"]:results.recordID.recordName];
        }
        [iBeaconSingleConfirmed addObject:results];
    };

    cursorOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *operationError)
    {
        AAPLPostManagerErrorResponse error = [self handleError:operationError];
        cursorCursor = [CKQueryCursor alloc];
        cursorCursor = cursor;
        postCursor = cursorCursor;
        NSLog(@"in block error & cursor & postCursor %ld %@ %@",(long)error,cursor,postCursor);
        [self.delegate performSelectorOnMainThread:@selector(refreshPicker:)  withObject:@"Teacher" waitUntilDone:YES];
    };
    [publicDatabase addOperation:cursorOp];
}
}

Now first time in to loadStudentContoller1n2Picker it works, downloads 3 records. Second time in via a button action it works, gets the next 4 records. i.e. the cursor is correctly saved and passed on. However third time in it resets itself and I get a copy of the first three records. Indeed it seems very inconsistent, sometimes its worse, first time it works, second time does nothing... Ahhhhhh...

REFrostedViewController: Opening storyboard view controllers from AppDelegate

I'm using the REFrostedViewController repo to have a drop down menu in my iOS app. I am using storyboards opposed to the creator's xib implementation. It works beautifully but I am having a problem implementing a new function in my app. I am trying to present a view controller using AppDelegate.m when I get a notification on my device.

Currently, I'm just trying to open a new view controller after the app has been launched for a few seconds. Since I'm trying to open it after a notification, I decided to put the code in my AppDelegate file. Whenever I run the code and debug it, I see all the values being allocated correctly but nothing happens.

Rundown: App launches -> first screen -> wait 6 seconds -> open new view controller -> nothing worked.

All attempts so far has given me no results and I'm not sure how to move from here. I'm looking for suggestions/ideas/possible answer on what I should do.

The usual process to open another view controller is:

// Init navigationController
NavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentController"];
// Init destination view controller
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"viewController"];
navigationController.viewControllers = @[vc];

// set destination to view controller
self.frostedViewController.contentViewController = navigationController;
[self.frostedViewController hideMenuViewController];

Let me know if there needs to be more information. Thanks!

Face visualisation and makeover iOS

I want to create an app like Modiface in iOS. Any tutorial to start with?

Thanks in advance.