mardi 5 mai 2015

How to disable Apple Watch auto sleep in an app?

I have a written an app for Apple Watch and I don't want the watch to go to sleep while my app is running. How can I disable the idle timer on watch?

How to edit one complex object in multiple screens in Android?

I'm trying to figure out best/correct way to edit one complex object on multiple screens in Android. I have Event which has a collection of Invites. Event is edited on one screen and Invites list is composed on another. User first edits event data then goes to address book like screen to add/remove invites then goes back to event screen and send all changes to server.

I'm using Xamarin and want to have same business logic code on both iOS and Android. On iOS I have Event object with InvitesList inside it. I pass InvitesList to InvitesController and it edits this list and this is basically it. Everything works as intended. Sample code:

public class Event {
  InvitesList Invites { get; private set; }
  public async Task Save() {
    await service.SaveEvent(this);
    await service.SyncContacts(Invites.New, Invites.Removed);
  }
}

My problem is that above scenario does not work with Android if I want to edit InvitesList in a separate activity. InvitesList knows how to load it data from server and it also tracks additions and deletions so Event object could figure out what server API calls it need to do later on. AFAIK my options are

  1. Create InviteListMemento and pass it back and forth between activities. I don't like it because I'll will have to serialize potentially large list of added Contacts or Contact object might be large (for example have images inside or maybe dozen of strings).
  2. Save InvitesList in static variable. This is ugly and I'd like to avoid this solution.

I don't like any of above solutions. Can anyone suggest a solution which would allow me to keep my business objects intact? I'd like to have Event object with InvitesList inside and also to be able to edit InvitesList in separate activity. Ideally I also would like to keep changes required only for Android to a minimum.

Keychain data can't be shared between apps

I've got keychain dumper working fine on an iPad Air. I have a bunch of apps where I am sharing keychain data. This works great. These apps are older and compiled under Xcode 4. I've got a jailbroken iPad and have used Keychain Dumper which sees all these apps data.

I now have a new iOS App (Cordova HTML-based) which I use a different keychain plugin for. It's compiled by xCode 6.

Keychain dumper (with -a) cannot see the data saved by this project, even though it persists and restores correctly. Even when the app is running, I cannot see the keychain data. It also cannot share the keychain data from the other apps even though I use the same bundle seed etc, and follow the same recipe I always did. It's writing in a different location or something.

Have the defaults for saving keychain data changed somehow?

Unable to set velocity of sprites correctly

I am making an asteriods-like app in iOS8. I have code that creates a laser shot and sets its velocity vector according to the facing of the ship. When the ship is oriented upwards on the screen, the code works correctly. When the ship is oriented downwards on the screen the sprite has no, or almost no, velocity along the y-axis. That is, the .dy component of physicsBody.velocity behaves as if it is near zero; the .dx component behaves correctly. LLDB reports the .dy component as what it should be, but the sprite moves incorrectly. Here is the relevant code:

func createLaser()->SKSpriteNode {
    let laserBeam = SKSpriteNode(imageNamed: "laserBeam")
    laserBeam.name = "laserBeam"
    laserBeam.position.x = shipNode.position.x
    laserBeam.position.y = shipNode.position.y
    laserBeam.physicsBody = SKPhysicsBody(circleOfRadius: 10.0)
    laserBeam.physicsBody?.dynamic = true
    laserBeam.physicsBody?.affectedByGravity = false
    laserBeam.zRotation = shipNode.zRotation
    laserBeam.physicsBody?.mass = 1.0
    laserBeam.physicsBody?.velocity.dx = kLaserSpeed * sin(shipNode.zRotation ) * -1 //TODO apply an impulse instead?
    laserBeam.physicsBody?.velocity.dy = kLaserSpeed * cos(shipNode.zRotation) * 1
    println("in create Laser ship rotation = \(shipNode.zRotation), dx = \(laserBeam.physicsBody?.velocity.dx), dy = \(laserBeam.physicsBody?.velocity.dy)")
    return laserBeam
}

Error with Json http request iOS

I am trying to work on Livelink restful services and get data in iOS Application. The documentation link for api is:

http://ift.tt/1OY65sS

Code I am using for getting response data is:

NSDictionary *authDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              @"XYZ",@"username",
                              @"ABC",@"password",
                              nil];
NSError *error;
NSData *requestData = [NSJSONSerialization dataWithJSONObject:authDict options:0 error:&error];
NSURL *url = [NSURL URLWithString:@"http://ift.tt/1EOCLwR"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];                                              
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; 

But in request reply I am not getting authentication result.When I log request reply,the log is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://ift.tt/mOIMeg">
<html xmlns="http://ift.tt/lH0Osb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>500 - Internal server error.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>500 - Internal server error.</h2>
  <h3>There is a problem with the resource you are looking for, and it cannot be displayed.</h3>
 </fieldset></div>
</div>
</body>
</html>

Could you please help me to get the Authentication ticket. Thanks in advance.

Feeding dynamic data to UICollectionView within UITableViewCell

Hello friendly swifters.

I am generating a table of cells.
each cell contains 2 labels, 1 button, 1 collectionview
each collectionview will display a collection of images

I can get my dynamic data to update the labels and buttons as needed.

I could use some help getting the collectionview cell to show my images. The collectionview prototype does have an imageview within it, which is linked to my collectionviewcell class.

example of empty collection views:
enter image description here

here's some code:

//My TableView 'cellForRowAtIndexPath

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:DeckTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! DeckTableViewCell

    let deck:PFObject = timeLineData.objectAtIndex(indexPath.row) as! PFObject

    let sequenceTemp = deck.objectForKey("Sequence") as! String

    cell.sequenceId.setTitle(deck.objectId, forState: UIControlState.Normal)
    cell.cardCountLabel.text = "\((count(sequenceTemp)/2))"

    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "(MM-dd) hh:mm:ss"
    cell.timeLabel.text = dateFormatter.stringFromDate(deck.updatedAt!)

    return cell
}


let images = ["2C.png", "3C.png", "4C.png", "5C.png", "6C.png", "7C.png", "8C.png", "9C.png", "10C.png", "JC.png", "QC.png", "KC.png", "AC.png"]

//My CollectionView 'cellForItemAtIndexPath

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell: TableCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! TableCollectionViewCell

    let image = UIImage(named: images[indexPath.row])

    cell.ImageView.image = image
    cell.ImageView.backgroundColor = UIColor.orangeColor()

    return cell
}

The collectionview cell is not updating, not even to orange.

thanks for your time.

(XCode) Error signal SIGTERM everytime I quit the iOS simulator

Everytime I quit the iOS Simulator using XCode the error "Thread 1: signal SIGTERM" shows up in the AppDelegate.swift file, right in the "class AppDelegate:___{" line. The only thing that shows up in the console is "(llbd)".

How can I fetch only object rows sent&mapped back from server when using RestKit+CoreData?

I am using RestKit 0.2.x with Core Data and following the standard tutorials, ie:

  • Create Core Data model and use mogenerator to make code
  • Instantiate object manager with base URL
  • Create managed object context and persistent store
  • Create entity mappings for all entities returned by my web service
  • Create response descriptors for all web service endpoints and entities
  • Add response descriptor to object manager

Everything seems to be "working" just fine ... I can call

[[RKObjectManager sharedManager] getObjectsAtPath:_requestPath parameters:_requestParameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

... all day long, and I then I keep handling with (as shown in the tutorials)

- (void)requestSuccess {
    NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:_entityName];
    fetchRequest.sortDescriptors = @[_defaultSortDescriptor];

    NSError *error = nil;
    requestData = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    [_delegate handleRequestSuccess:self withData:requestData];
    //[self cleanupRequestBeforeSuccessWithData:requestData];
    [self completeRequest];
}

Now the problem is that at least by default, RestKit+CoreData actually persists your GET'ted objects to its own persistence store, or something like that. I'll explain the "cleanupRequest..." in a moment.

That kind of defeats the purpose of trying to allow the users to specify parameters at the level of the web service client, because all of the objects seem to end up in the same place anyway.

For instance, let's say I have a method /api/endpoint?queryString and I call it with two different sets of parameters:

[[RKObjectManager sharedManager] getObjectsAtPath:@"/api/endpoint" parameters:PARAMS_ONE success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

[[RKObjectManager sharedManager] getObjectsAtPath:@"/api/endpoint" parameters:PARAMS_TWO success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [self requestSuccess];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    [self requestError:error];
}];

If I then blindly follow the tutorials about how to retrieve my objects, my callbacks are then identical!

NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EndpointDataTransferObject"];
fetchRequest.sortDescriptors = @["endpointDataTransferObjectID"];

NSError *error = nil;
requestData = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

The result, of course, is that the my delegate gets sent (pseudocode) requestData WHERE PARAMS_ONE on the first call, and then requestData WHERE PARAMS_ONE UNION requestData WHERE PARAMS_TWO on the second call.

Now all I really want is to be able to conduct the NSFetchRequest on only those items mapped from the web service. I think this is a totally reasonable expectation, so clearly I am missing something because whoever wrote this library is much more clever than I.

For instance, if I could somehow get an NSArray of all the objects from the two parameters it provides in the success block (RKRequestRequestOperation *o, RKMappingResult *m) - and if I can, please tell me how!!! - then my problem would be solved, and I could enjoy the caching without having to worry about whether my filters are being ignored.

What I do not want to do, however, is this:

  • Call getObjectsAtPath: parameters: success: failure: with parameters and/or path representing a sort of "server-side" predicate
  • On success, create a NSFetchRequest and a client-side predicate that mirrors my server-side predicate

This approach seems really really dumb, and yet, I don't know any better. But I refuse to do that. It is error-prone, redundant, and potentially resource-intensive.

So instead, I've opted to add a little method cleanupRequestBeforeSuccessWithData at the end of my success callback before calling completion:

- (void)cleanupRequestBeforeSuccessWithData:(NSArray *)managedObjects {
    NSManagedObjectContext *managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;

    for (NSManagedObject *o in managedObjects) {
        [managedObjectContext deleteObject:o];
    }

    NSError *error = nil;
    [managedObjectContext save:&error];
}

This is ugly but it sure gets the job done. Now it totally empties the cache, but I'd rather have to make requests over and over again than to form "server-side" predicates with URL's and then form client-side NSPredicates.

What am I missing about how this is supposed to work? Clearly, I'm missing something big.

Get Value from AnyObject Response Swift

How to get the values of id,content,name from the response from the server. The response from the server is as an AnyObject and if I print, it appears like given below...

{
 content = xxxx
 id = 22
 name = yyyy
}

Thanks in advance.

App Wide Themes in Swift on iOS

I have a solution, but to me it looks like a very hacky and not very elegant solution. But I searched, and searched, and could not find anything else. Maybe someone can suggest a better solution?

So, the problem, I want to have one file where I define all the colors and fonts and such of my app. I created a Style struct with a bunch of static vars like this:

struct Style{
    static var colorA = UIColor.redColor()
    static var colorB = UIColor.blackColor()
    static var titleText = colorA
    static var mainText = colorA
    static var backColor = colorB
    static var callBackColor = backColor
}

I have to use start var because I want to be able to reference previously declared variables in the definitions of new variables, and that's the only way I could make it work.

Overall above works well. In my code I can always reference a color or other purport as Style.titleText, for instance. So it looks like a good solution.

However, then I decided to add themes. To do so I added a static method called theme1 that overwrites some of the static vars from above and added a theme selector. Simple enough:

struct Style{
    static var colorA = UIColor.redColor()
    static var colorB = UIColor.blackColor()
    static var titleText = colorA
    static var mainText = colorA
    static var backColor = colorB
    static var callBackColor = backColor

    static func themeSelector(){
        // some logic loading defaults and running appropriate theme function bellow
    }

    static func theme1(){
        static var backColor = UIColor.greenColor()
        static var callBackColor = UIColor.greenColor()
    }
}

But then I ran into a problem, how to fire the themeSelector method? I tried overriding the initializer method and converting my struct to a class, but the initializer function would not fire in time, so some of variables that relied on the Style settings in their declaration statements would not load with updated theme settings, but rather with the defaults.

I also tried putting the call into the didFinishLaunchingWithOptions method of the AppDelegate, but same result as above.

I ended up doing something really idiotic looking, declaring a variable in my ViewController class like so:

var loadThem: Bool = {
    Style.themeSelector()
    return true
}()

This works, but..... really, is that the best way. Is there a better way to make themes? Is there a better way to call a function on load of a class or structure (overriding load method is not an option any more as of Swift 1.2). So, is there a better way?

Is it possible to implement a rating system with game center?

Is is possible to use iOS Game Center to implement a rating system for multiplayer games, where a player's rating go up if they win battles and down if they lost? From my understanding, it's primary use is to store high scores and achievements.

Get UITextView Gesture (To Identify Location of Tap/LongPress)

I'm rather confident [editable] UITextView's become firstResponder when a long press or tap gesture occurs within the scrollView. I want to identify where in the view this touch occured. Digging through the documentation and source code didn't yield me much. I might be going about this wrong. My concern is a race condition if I just add my own tap recognizer (how can I be sure it is called before the textView's delegate methods).

For practical clarification, I want to call two similar functions from a delegate function (editingDidBegin) but depending if they touched the left or right half of the text view, I want to call either of the two.

Position changed when changing the anchorpoint of the (sprite) node

I am adding the main node and the child nodes to it. All nodes should be rotating from a variable anchorpoint.

So when I change the anchorpoint of the main node, the distance between the child nodes and the main nodes is being changed(the distance between the childnodes remain the same).

Why is this happening and how can it be solved?

Mach-0 Linker error when trying to run watchKit app on Simulator

When I try to build and run my app with a watchKit extension, here is the error screen that I see. If you would like to see a larger image, simply right click and hit open in new Tab. enter image description here

Can't get holidays from Google calendar

I am create calendar by get events from Google Calendar. I can get and sync events i created on app or on google calendar (the same account). But i cant get list holidays from Google Calendar, it always notifice error.

NSErrorFailingURLKey=http://ift.tt/1Jiz6se, NSLocalizedDescription=Request failed: unauthorized (401)

Compiler error after adding a new Configuration in project

I encountered an issue after setting up a new value for Configuration when building (after reading the following post: Different App Icons for your iOS Beta, Dev, and Release builds). The error message is as follows:

ld: file not found: /Users/.../Library/Developer/Xcode/DerivedData/SomeAppName-.../Build/Products/Debug-iphoneos/http://ift.tt/1dLIb2W

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm not sure how to fix it, checked and double checked with the article and I did follow everything as explained.

CGRectMake 4 Lines with horizontal displacement for each line?

I have a method:

-(void) generateButtons {
int positionsLeftInRow = BUTTONS_PER_ROW;
int j = 0;

for (int i = 0; i < [self.Model.buttons count]; i++) {
    NSInteger value = ((Model *)self.Model.buttons[i]).value;

    ButtonView *cv = [[ButtonView alloc] initWithFrame:CGRectMake((i % BUTTONS_PER_ROW) * 121 + (i % BUTTONS_PER_ROW) * 40 + 205, j * 122 + j * 40 + 320, 125, 125) andPosition:i andValue:value];

    if (!((Model *)self.Model.buttons[i]).outOfPlay) {
        [self.boardView addSubview:cv];


        if ([self.Model.usedButtons containsObject: self.Model.buttons[i]]) {

            [self.usedButtons addObject: cv];

            [cv flip];

        }
    }

    if (--positionsLeftInRow == 0) {
        j++;
        positionsLeftInRow = BUTTONS_PER_ROW;
    }
}

}

So, my question is, how to make a horizontal displacement for each line, that the second line is displaced from 1st and 3rd for example.

Can't quite get my CGAffineTransform animation correct

I am trying to rotate a view around a semi-circle and I have the positioning and rotation of the view correct, however when I try the animation, everything gets screwed up.

Here is my code for the initial placement of the pointer:

CGAffineTransform transform = CGAffineTransformMakeTranslation(x, y);
transform = CGAffineTransformRotate(transform, radians);
self.pointerView.transform = transform;

I figured the code for the animation would be pretty much the same thing, but with an animation block, but the view to animate starts way off to the right where it is supposed to be and animates to the correct position. Not sure what I am doing wrong. Here is the animation code:

[UIView animateWithDuration:0.5 delay:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{
           CGAffineTransform atransform = CGAffineTransformMakeTranslation(x, y);
            self.pointerView.transform = CGAffineTransformRotate(atransform, radians);
        } completion:NULL];

Create API Class to handle JSON Data Swift

I'm extremely new to handling JSON Data in Swift, and almost just as new to Swift. In a Playground I wrote a whole bunch of code that parsed JSON Data out.

However I realized I don't want to copy and paste this code into every view controller that uses only some of the data. I want to create a custom class that handles the json data.

Here is a bit of my code:

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!



url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()

I then attempted to create a class like this:

class JsonClass {

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!


init() {
 url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()


}

I thought that within a new class I would be able to do something like this:

let jsonAPI = JsonClass()
println(jsonAPI.status)
println(jsonAPI.message)

etc...

However, any attempt to access an instance of the JsonClass results in every JsonClass property having a value of nil.

What are my next steps to accessing this data using instances of this class?

Using CABasicAnimation in a UIButton subclass

I would like to animate the transition of a button's border color when the highlighted state changes. I have subclassed UIButton and overridden setHighlighted, where I perform a CABasicAnimation. The problem is, this code is executed but the border color instantly changes - it doesn't animate from one color to the next. This same code worked when I used it in the view controller, causing me to wonder if CABasicAnimation doesn't work in a UIButton subclass, or what else is necessary to ensure this animation occurs.

How can I animate a button's CALayer's borderColor in the button subclass?

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (highlighted) {
        [self highlight];
    } else {
        [self unhighlight];
    }
}

- (void)highlight {
    UIColor *currentLayerColor = [[UIColor alloc] initWithCGColor:self.layer.borderColor];
    UIColor *newLayerColor = [currentLayerColor colorWithAlphaComponent:0.25];

    CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
    color.fromValue = (__bridge id)currentLayerColor.CGColor;
    color.toValue   = (__bridge id)newLayerColor.CGColor;
    self.layer.borderColor = newLayerColor.CGColor;

    color.duration = 2.0;
    [self.layer addAnimation:color forKey:nil];
}

- (void)unhighlight {
    UIColor *currentLayerColor = [[UIColor alloc] initWithCGColor:self.layer.borderColor];
    UIColor *newLayerColor = [currentLayerColor colorWithAlphaComponent:1.0];

    CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
    color.fromValue = (__bridge id)currentLayerColor.CGColor;
    color.toValue   = (__bridge id)newLayerColor.CGColor;
    self.layer.borderColor = newLayerColor.CGColor;

    color.duration = 2.0;
    [self.layer addAnimation:color forKey:nil];
}

IOS/MapKit: Launch Native Map App by Clicking on MKPlacemark

IOS newb just learning Mapkit. I load a map in my app using MKPlacemark. However some users may want to use more advanced features such as driving directions and for this, I think, they would be better off launching the native app on top of mine (with my app still open in the background when they finish with the regular map app)

I know how to launch the native app from my app using MKMapItem. However, s there a way to launch the native app only after the user touches the place mark.

Here is code I am using.

-(void) geoCodeAndMapIt {
    NSString* location = @"156 University Ave, Palo Alto, CA 94301";
    NSLog(@"going to map this address:  %@",location);
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
             completionHandler:^(NSArray* placemarks, NSError* error){
                 if (placemarks && placemarks.count > 0) {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     MKPlacemark *placemark = [[MKPlacemark alloc]
                                               initWithPlacemark:topResult];
                     MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(placemark.coordinate, 5000, 5000);//5000 is meters
                     region.span.longitudeDelta /= 8.0;
                     region.span.latitudeDelta /= 8.0;

                     [self.mapView setRegion:region animated:YES];
                     [self.mapView addAnnotation:placemark];

 //                    The following MKMapItem class launches the full blown native app as opposed to the one in Idaru.  Commenting it out causes the map to load in the app.  Otherwise, it fires up the native map app immediately in place of the previous app.

                     MKMapItem *mapItem = [[MKMapItem alloc]initWithPlacemark:placemark];
                     mapItem.name = self.contact.first;
                     mapItem.phoneNumber = self.contact.tel;

                     NSDictionary *options = @{
                                               MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                               MKLaunchOptionsMapTypeKey:
                                                   [NSNumber numberWithInteger:MKMapTypeSatellite],
                                               MKLaunchOptionsShowsTrafficKey:@YES
                                               };
                     [mapItem setName:@"Name of your location"];
                     [mapItem openInMapsWithLaunchOptions:options];*/


                 }
             }
 ];


    [mapItem openInMapsWithLaunchOptions:options];
}

Thanks for any suggestions.

UIPageControl problems, Objective-C

I have been working on implementing UIPageViewController for some time now. I have went through many problems that i managed to solve by myself and with some extra help. Now i am stuck with the last part and that is the UIPageControl.

I got two problems that i would like some help with:

Problem 1: Is there any simple way to resize the dots for the pageControl?

Problem 2: This is how it is built:

enter image description here

I know it is hard to see but i will explain them starting from the upper left corner and going to right. First VC is simply a Navigation Controller pointing to a UITableViewController.

in the second row the first VC is the datasource delegate for the UIPageVIewController. The one next to it is the PageViewController, The two UITableView's next to it is the "pages" that are in the UIPageViewController. And the last one is the PageContentViewController.

So i added this code in viewDidLoad to the datasource VC meaning the first VC in the second row:

self.navigationController.delegate = self;
CGSize navBarSize = self.navigationController.navigationBar.bounds.size;
CGPoint origin = CGPointMake( navBarSize.width/2, navBarSize.height/2 );
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(origin.x, origin.y+16,
                                                                   0, 0)]; //Here added 45 to Y and it did the trick



self.pageControl.pageIndicatorTintColor = navbarColor;
self.pageControl.currentPageIndicatorTintColor = [UIColor lightGrayColor];

[self.pageControl setNumberOfPages:2];

and

- (void)navigationController:(UINavigationController *)navigationController     willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    int index = [self.navigationController.viewControllers indexOfObject:viewController];
    self.pageControl.currentPage = index;  }

Which gives me this result:

enter image description here

Which is perfect, I can swipe right and left and the PageControl shows the right indicator etc. However when i leave the "UIPageViewController" meaning when i click back. The PageController still appears in the first VC in the first picture. Why does it tag along and not get removed and how can i solve this?

If you need extra codes / pictures that would make it easier to understand just tell me. Thank you!

Google Maps for iOS - How can you tell if a marker is within the bounds of the screen?

I'm trying to figure out a straightforward way to determine in Google Maps for iOS if a given GMSMarker is within the bounds of the visible map. There seems to be solutions for this in the Javascript API but other than perhaps doing some complex reasoning based on this post there doesn't seem to be a way.

Best approach to implement this design [ios]

What would be the best approach to implementing a design like the one below?

Couple of things: - Level cell can fall between any 4 cells on the grid - Whole whole board is scrollable

I'm leaning toward UICollectionView but I'm not exactly sure how to do the "level cell." One of the approach might be to split the level image into four and draw them on each cell? I'm not sure if that's the best solution, however.

More info: - The gray boxes are just game actions. Based on the actions, the app determine if they reached the next level. In the design, it only shows level 6 but it will really have level 1,2,3.. all the way up to 200.

level grid design

how to hide/show a button in swift

I'm trying to have a if statement that will make a button be hidden when a label displays a certain status and appear when the label says something else. The name of label is Status and when is shows "Closed" I want it hidden and when it shows "Open" it will appear.

    var query3 = PFQuery(className:"Status_of_game")
    query3.findObjectsInBackgroundWithBlock{

    (namelist3: [AnyObject]!, error : NSError!) -> Void in

    for list3 in namelist3 {

    var output = list3["StatusType"] as String

    self.Status.text = output

     println(output)

     if self.Status.text == "Closed" {

     Purchase().enable = false
            }

        }

    }

}

Centering the camera on the character

I am a beginner and I have started my first project. It should be a little game where you can run to the left and to the right. But I don't know how to set the camera settings.

I'd be very thankful if you could help me, tell me how I can improve my code and what is wrong.

Here is my Code:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var ground:SKSpriteNode = SKSpriteNode()
var hero: MPCharacter!
var tree:MPTree!

override func didMoveToView(view: SKView) {

    backgroundColor = UIColor(red: 155.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0)
    self.anchorPoint = CGPointMake(0.5, 0.5)

    // --> hero <--
    hero = MPCharacter()
    hero.position = CGPointMake(frame.size.width/2, view.frame.size.height/2)
    hero.zPosition = 100
    hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(hero.size.width, hero.size.height))
    hero.physicsBody!.dynamic = true

    addChild(hero)

    // --> ground <--
    ground = SKSpriteNode(imageNamed: "ground")
    ground.size = CGSizeMake(frame.size.width, frame.size.height/3)
    ground.position = CGPointMake(frame.size.width/2, frame.size.height/2 - ground.size.height)

    ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(frame.size.width, ground.size.height - 25))
    ground.physicsBody!.dynamic = false

    addChild(ground)

    // --> Tree <--
    tree = MPTree()
    tree.position = CGPointMake(frame.size.width/2, ground.size.height + tree.size.height/3 - 10)
    tree.zPosition = 10

    tree.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(tree.size.width, tree.size.height - 10))
    tree.physicsBody!.dynamic = false

    addChild(tree)

    // --> Physics <--
    self.physicsWorld.gravity = CGVectorMake(0, -5.0)
    self.physicsWorld.contactDelegate = self

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch:AnyObject in touches {

        let location = touch.locationInNode(self)

        if location.x < CGRectGetMidX(self.frame) {
            hero.physicsBody!.velocity = CGVectorMake(0, 0)
            hero.physicsBody!.applyImpulse(CGVectorMake(-5, 10))
        }
        else {
            hero.physicsBody!.velocity = CGVectorMake(0, 0)
            hero.physicsBody!.applyImpulse(CGVectorMake(5, 10))
        }
    }
  }
}

Skip onboarding screens after appUser has scrolled through all screens?

How can I ensure that the appUser does not have to slide through all of the onboarding screens each time they open the app? I have 4 onboarding screens leading to a signup/login screen.

Content of the UIViewController doesn't show up even though the UINavigation bar is there

So I'm trying to switch from one UIViewController to another using the navigation controller. I know for sure that the new controller goes successfully through the custom init method and creates two UIBarButtons. However, the content of the screen (4 labels, 3 textfields, 1 UIImageView) doesn't show up. Instead, I just see a grey screen.

Passing the NSLog message through the ViewDidLoad,ViewWillLoad and ViewWillAppear showed that all these were successfully executed.

Here is the gitHub repo if you want to take a look: http://ift.tt/1cjGCZv

Here is the code that I use to pass a new controller:

// Create a new student and add it to the store
  Student* newStudent = [[StudentStore sharedStore] createStudent];

StudentDetailViewController *detailViewController = [[StudentDetailViewController alloc] initForNewStudent:YES];

detailViewController.student = newStudent;

detailViewController.dismissBlock = ^{
    [self.tableView reloadData];
};

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

navController.modalPresentationStyle = UIModalPresentationFormSheet;

[self presentViewController:navController animated:YES completion:NULL];

Animation is not working as expeced

I implemented corePlot in xcode and I'm using the pie chart. I'm trying to create a 3d flip animation while the chart reloads. Here is the code:

CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
scaleAnimation.toValue = [NSNumber numberWithFloat:0.5];
scaleAnimation.duration = 1.0f;
scaleAnimation.removedOnCompletion = NO;
[self.pieChart addAnimation:scaleAnimation forKey:@"scale"];

[self.pieChart reloadData];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
animation.fromValue = [NSNumber numberWithFloat:0.5];
animation.toValue = [NSNumber numberWithFloat:1.0];
animation.duration = 1.0f;
[self.pieChart addAnimation:animation forKey:@"scale"];

I didn't get desirable effects. I think what's happening is, both animations are happening at once. (Though I'm not sure that is what's happening.)

Also, is it possible to add z-depth? If so, how?

platform.hpp file not founde [iOS]

I try import parse with cocoapods in my project but have error like platform.hpp file not founde, how fix it? iOS trouble with libzmq

SceneKit animate node along path

I have a box node

_boxNode = [SCNNode node];
_boxNode.geometry = [SCNBox boxWithWidth:1 height:1 length:1 chamferRadius:0];
_boxNode.position = SCNVector3Make(0, 0, -2);
[scene.rootNode addChildNode:_boxNode];

I have a path

CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(-2, -2, 4, 4), nil);

I want to have my box travel along my path.

How do I do this in SceneKit?

MPMusicPlayerController volume slider disappeared

I have noticed that in iOS 8.3, the MPMusicPlayerController volume slider in my app is not displayed at all. It was being displayed in earlier iOS versions. No changes were made to the app. Is anyone experiencing this problem in their apps?

Watchkit -application: handleWatchKitExtensionRequest error

I'm getting the following error when requesting a dictionary of XML items via the above method:

> NSLocalizedDescription=The UIApplicationDelegate in the iPhone App never called reply() in -[UIApplicationDelegate application:handleWatchKitExtensionRequest:reply:]

I have no problem passing an NSDictionary consisting of an NSMutableArray of NSStrings.

From the interface controller:

- (void) requestFeedsFromPhone
{
    [WKInterfaceController openParentApplication:@{@"request":@"feeds"}
                                       reply:^(NSDictionary *replyInfo, NSError *error) {

                                           // the request was successful
                                           if(error == nil) {

                                               // get the array of items
                                               NSMutableDictionary *tempDictionary = replyInfo[@"feeds"];


                                               NSLog(@"tempDictionary: %@", tempDictionary[@"feedsArray"]);
                                               self.feeds = tempDictionary[@"feedsArray"];
                                               [self setupTable];
                                           }
                                           else{
                                               NSLog(@"ERROR: %@", error);
                                           }
                                       }];
}

In the app delegate:

- (void) application:(UIApplication *)application
handleWatchKitExtensionRequest:(NSDictionary *)userInfo
           reply:(void (^)(NSDictionary *))reply
{

    MasterViewController *mainController = (MasterViewController*)  self.window.rootViewController;

    //this is the troublesome line - calling this method results in the error
    NSDictionary *feedsDictionary = [mainController returnFeedsDictionary];

    reply(@{@"feeds": feedsDictionary});
}

In the MasterViewController:

-(NSDictionary *) returnFeedsDictionary
{

    NSURL *url = [NSURL URLWithString:@"http://ift.tt/1PmtTl3"];
    SeparateParser *separateParser = [[SeparateParser alloc] initWithURL:url];
    [separateParser parse];
    NSArray *tempArray = [separateParser returnFeeds];
    return @{@"feedsArray": tempArray};

}

The returnFeeds method returns an NSMutableArray of NSMutableDictionarys filled with NSMutableStrings (title, link, imageURL, etc).

I'm assuming my problem is that some of my data isn't property list compliant but I thought arrays, strings, and dictionaries were acceptable.

Show spash screen each time app becomes active

I want the splash screen to be displayed each time app becomes active. I have created a function showSplash which I call in applicationDidBecomeActive

-(void)showSplash
{
    UIImageView *splashScreen = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"Default.png"]];
    [self.window.rootViewController.view addSubview: splashScreen];
    [self.window makeKeyAndVisible];
    NSLog(@"begin splash");
    [UIView animateWithDuration: 4.2
                          delay: 0.5
                        options: UIViewAnimationOptionCurveEaseOut
                     animations: ^{  
                         splashScreen.alpha = 0.0;
                     }
                     completion: ^ (BOOL finished) {
                         [splashScreen removeFromSuperview];
                         NSLog(@"end splash");
                     }
     ];
}  

This is how I call this function :

- (void)applicationDidBecomeActive:(UIApplication *)application {
[self showSplash];
}

But no splash screen appears. Please correct me.

Popover doesn't center on button

I am trying to center a popover on a button. I can't seem to figure out where I might be going wrong. Instead of the arrow being in the middle of the button, it is off center by half the width of the screen.

 @IBAction func buttonClicked(sender: AnyObject){
    var popoverViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ServiceOptions") as! ServiceOptionsPopover
    popoverViewController.delegate = self
    popoverViewController.modalPresentationStyle = .Popover
    popoverViewController.preferredContentSize   = CGSizeMake(300, 300)

    let popoverPresentationViewController = popoverViewController.popoverPresentationController

    popoverPresentationViewController?.permittedArrowDirections = .Up
    popoverPresentationViewController?.delegate = self
    popoverPresentationViewController?.sourceView = sender as! UIButton
    popoverPresentationViewController?.sourceRect = sender.frame

    presentViewController(popoverViewController, animated: true, completion: nil)
}

Swift - Getting address from coordinates

I have a local search that creates annotations for each search result. I'm trying to add an call out accessory to each of the annotations, and once that will be pressed, the Maps app will open and set directions on how to get to the certain location.

The problem that I am having is that in order for the call out accessory to work correctly, you have to get the address using place marks in the Address Book import. I've done plenty of searching and can't figure out how to set it up correctly where I can covert the annotation coordinates into a kABPersonAddressStreetKey so the Maps app can read it correctly. Below is my code for the search function, and the open Maps app function.

func performSearch() -> MKMapItem {

    matchingItems.removeAll()
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = searchText.text
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.startWithCompletionHandler({(response:
        MKLocalSearchResponse!,
        error: NSError!) in

        if error != nil {
            println("Error occured in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")
        } else {
            println("Matches found")

            for item in response.mapItems as! [MKMapItem] {
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")

                self.matchingItems.append(item as MKMapItem)
                println("Matching items = \(self.matchingItems.count)")

                var annotation = MKPointAnnotation()
                var coordinates = annotation.coordinate
                var location = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)
                var street = // Insert code here for getting address from coordinates
                var addressDictionary = [String(kABPersonAddressStreetKey): street]
                var placemark = MKPlacemark(coordinate: coordinates, addressDictionary: addressDictionary)
                var mapItem = MKMapItem(placemark: placemark)
                return mapItem

                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                self.mapView.addAnnotation(annotation)

            }
        }
    })
}


func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!,
    calloutAccessoryControlTapped control: UIControl!) {
        let location = view.annotation as! FirstViewController
        let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
        location.performSearch().openInMapsWithLaunchOptions(launchOptions)
}

Any help would be greatly appreciated, thanks in advance.

Reusing pixels shaders with different uniform parameters in iOS metal

I'm having a problem reusing my metal pixel and vertex shaders across different objects with different uniform parameters. I'm guessing its got something to do with my using my command buffer incorrectly.

When I run my metal application, the geometry draw correctly, but only the uniforms for the final call to

renderCommand setFragmentBuffer:uniform_info offset:0 atIndex:UNIFORM_INFO_BUFFER_INDEX];

Seems to write data to the pixel shader.

I've cut-n-pasted (and edited) my render loop here. I'm looking for an example of how to reuse my pixel shader multiple times during a single render pass with different uniforms passed in.

  CAMetalLayer *metalLayer = [metal_info.g_iosMetalView getMetalLayer];

  id <CAMetalDrawable> frameDrawable;
  while (!frameDrawable){
     frameDrawable = [metalLayer nextDrawable];
  }
  MTLRenderPassDescriptor *mtlRenderPassDescriptor;
  mtlRenderPassDescriptor = [MTLRenderPassDescriptor new];
  mtlRenderPassDescriptor.colorAttachments[0].texture = frameDrawable.texture;
  mtlRenderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionLoad;
  mtlRenderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 1.0, 1.0);

  mtlRenderPassDescriptor.depthAttachment.texture = metal_info.g_depthTexture;
  mtlRenderPassDescriptor.depthAttachment.loadAction = MTLLoadActionClear;
  mtlRenderPassDescriptor.depthAttachment.storeAction = MTLStoreActionStore;
  mtlRenderPassDescriptor.depthAttachment.clearDepth = 1.0;

  // Create My one and only command buffer
  id <MTLCommandBuffer> mtlCommandBuffer = [metal_info.g_commandQueue commandBuffer];

  int n = RendererInfo.fact.GetActiveCount();

  // loop through all the objects I have (I'm having trouble with 2)
  Object* curObj = NULL;
  for (int obj_i = 0 ; obj_i < n ; ++obj_i)
  {
     // create one render encoder for each object
     id <MTLRenderCommandEncoder> renderCommand = [mtlCommandBuffer renderCommandEncoderWithDescriptor: mtlRenderPassDescriptor];

     memcpy([metal_info.g_projectionMatrix contents], &metal_info.g_Projection, sizeof(Matrix4f));         
     Matrix4f *view = RendererInfo.cam->GetViewMatrix();
     memcpy([metal_info.g_viewMatrix contents], view, sizeof(Matrix4f));

     [renderCommand setFrontFacingWinding:MTLWindingCounterClockwise];
     [renderCommand setCullMode:MTLCullModeBack]; 

     [renderCommand setViewport: (MTLViewport){ 0.0, 0.0,
        (double)metal_info.g_metal_width,
        (double)metal_info.g_metal_height,
        0.0, 1.0 }];

     [renderCommand setRenderPipelineState:metal_info.g_pipelineState];
     [renderCommand setDepthStencilState:metal_info.g_depthState];


     curObj = RendererInfo.fact.GetObjectAtIndex(obj_i);

     id<MTLBuffer> vertices = curObj->GetVertexBuffer();
     id<MTLBuffer> indicies = curObj->GetIndexBuffer();         
     int indexCount = curObj->GetIndexCount();

     id <MTLTexture> texture = objTexture->GetAsset();
     [renderCommand setFragmentTexture:texture atIndex:0];         

     memcpy([metal_info.g_shaderUniformInfo contents], curObj->GetUniformInfo(), curObj->curObj->GetUniformInfoSize());

     [renderCommand setVertexBuffer:vertices                       offset:0 atIndex:VERTICES__INDEX];
     [renderCommand setVertexBuffer:metal_info.g_viewMatrix        offset:0 atIndex:VIEW_MATRIX_BUFFER_INDEX];
     [renderCommand setVertexBuffer:metal_info.g_projectionMatrix  offset:0 atIndex:PROJECTION_MATRIX_BUFFER_INDEX];

     [renderCommand setFragmentBuffer:metal_info.g_shaderUniformInfo  offset:0 atIndex:UNIFORM_INFO_BUFFER_INDEX];

     [renderCommand drawIndexedPrimitives:MTLPrimitiveTypeTriangle
                               indexCount:indexCount
                               indexType:MTLIndexTypeUInt32
                             indexBuffer:indicies
                       indexBufferOffset:0];

     [renderCommand endEncoding];
  }
  [mtlCommandBuffer presentDrawable:frameDrawable];
  [mtlCommandBuffer commit];

I can also post the pixel shader if you want, but when I've coded to only render one object at a time, the shader works correctly.

UIImageView in UICollectionVIew does not display image until "cell" is clicked on

In my collectionView, each cell has an image. The image is pulled from the web with a URL obtained from mySQL database. The entire code of my UICollectionView is here, and the cells are custom made:

#import "DealsCollectionView.h"
#import "DealsCell.h"
#import "DealsModel.h"
#import "Deal.h"

@interface DealsCollectionView ()
{
DealsModel *_homeModel;
}

@property UIActivityIndicatorView *spinner;
@property NSMutableArray *deals;
@property NSCache *imageCache;

@end

@implementation DealsCollectionView

-(void)itemsDownloaded:(NSArray *)items
{
// This delegate method will get called when the items are finished downloading

// Set the downloaded items to the array
_deals = [items copy];

[_spinner stopAnimating];

// Reload the table view
[self.collectionView reloadData];
}


- (instancetype) initWithCollectionViewLayout:(UICollectionViewLayout *)layout
{
self = [super initWithCollectionViewLayout:layout];

if (self) {
    // alloc and init the various (Mutable)Array properties
    self.deals = [[NSMutableArray alloc] init];
    self.imageCache = [[NSCache alloc] init];

    // Set Title
    self.navigationItem.title = @"Deals from Our Sponsors";



    // Create new HomeModel object and assign it to _homeModel variable
    _homeModel = [[DealsModel alloc] init];

    // Set this view controller object as the delegate for the home model object
    _homeModel.delegate = self;

    // Call the download items method of the home model object
    [_homeModel downloadItems];

}

return self;
}


- (void)viewDidLoad {
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = NO;

// Create a spinner
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

spinner.center = CGPointMake(screenWidth/2.0, screenHeight/5.0);
spinner.hidesWhenStopped = YES;
[self.view addSubview:spinner];
[spinner startAnimating];
_spinner = spinner;



// Do any additional setup after loading the view.

UINib *cellNib = [UINib nibWithNibName:@"DealsCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"dealCell"];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _deals.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DealsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dealCell" forIndexPath:indexPath];

// Configure the cell
Deal *thisDeal = [_deals objectAtIndex:indexPath.row];

UILabel *nameLabel = (UILabel *) [cell viewWithTag:1];
nameLabel.text = thisDeal.name;

UILabel *offerLabel = (UILabel *) [cell viewWithTag:2];
offerLabel.text = thisDeal.offer;

UILabel *descriptionLabel = (UILabel *) [cell viewWithTag:3];
descriptionLabel.text = thisDeal.businessDescription;

UILabel *addressLabel = (UILabel *) [cell viewWithTag:4];
addressLabel.text = thisDeal.address;



// Configure the image
UIImageView *imageView = (UIImageView *) [cell viewWithTag:6];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.clipsToBounds = YES;

UIImage *dealLargeImage = [self.imageCache objectForKey:thisDeal.largeImage];
imageView.image = dealLargeImage;
if (dealLargeImage == nil) {

    NSURLSessionConfiguration *sessionConfig =
    [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate: self delegateQueue:nil];
    NSURLSessionDataTask *imageData = [session dataTaskWithURL:[NSURL URLWithString: thisDeal.largeImage]
                                             completionHandler:^(NSData *data,
                                                                 NSURLResponse *response,
                                                                 NSError *error) {
                                                 // handle NSData
                                                 UIImage *image = [UIImage imageWithData:data];
                                                 //thisDeal.image = image;
                                                 [self.imageCache setObject:image forKey:thisDeal.largeImage];
                                                 imageView.image = image;

                                                 dispatch_async(dispatch_get_main_queue(), ^{
                                                     [self.collectionView reloadData];
                                                 });
                                             }];
    [imageData resume];
}

return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(20, 10, 20, 10); // top, left, bottom, right
}

The code for my custom UICollectionView cells are pretty much entirely blank, except for the XIB. The cell will appear, with all the labels set appropriately, etc. However, the image of the imageView is shown as black (the background color), until I click on it, in which case that cell's imageView (and only that cell's imageView) has its image appear. I'm wondering how I can get these images to appear as the view loads, rather than having to click on them.

MKMapView zoom to fit annotations while locking center

I'm trying to zoom to fit annotations on a map while locking the center and providing some insets.

- (void)fitAnnotations:(NSArray *)annotations edgeInsets:(UIEdgeInsets)insets
{
    CLLocationCoordinate2D originalCenter = self.centerCoordinate;
    MKMapRect mapRect = MKMapRectNull;

    for (id<MKAnnotation> annotation in annotations) {
        MKMapPoint p = MKMapPointForCoordinate([annotation coordinate]);
        mapRect = MKMapRectUnion(mapRect, MKMapRectMake(p.x, p.y, 0, 0));
    }

    mapRect = [self mapRectThatFits:mapRect edgePadding:insets];
    MKCoordinateRegion mapRegion = MKCoordinateRegionForMapRect(mapRect);

    // we now try to go back to the original center, while increasing the span by neccessary amount
    MKCoordinateSpan centeringDelta = MKCoordinateSpanMake(fabs(mapRegion.center.latitude - originalCenter.latitude), fabs(mapRegion.center.longitude - originalCenter.longitude));
    mapRegion.center = originalCenter;
    mapRegion.span.latitudeDelta += centeringDelta.latitudeDelta * 2.0;
    mapRegion.span.longitudeDelta += centeringDelta.longitudeDelta * 2.0;
    mapRegion = [self regionThatFits:mapRegion];
    [self setRegion:mapRegion animated:YES];
}

The first part of the code here works as expected: it zooms to fit while respecting the insets. However, it shifts the center.

I try to re-adjust the center after that, but it fails. I'm not sure if my math on the re-centering is correct.

Does Apple provide a C documentation of their Operating Systems and where is it?

I need help finding the Apple documentation (if it even exists) but it appears that there is no documentation. (or am I asking a completely wrong question)

How to use my own root certificate in iOS Secure Transport API?

I'm trying to use Apple's Secure Transport API on top of an established transport layer, with my own root certificate. I have my root certificate as a SecCertificateRef, but I can't figure out how to make it trusted.

I've examined the following functions, each of which seems tantalizingly close to what I need:

  • SSLAddDistinguishedName() is unimplemented;
  • SSLSetTrustedRoots() is deprecated;
  • SSLSetCertificateAuthorities() is for client authentication only.

If I could override the SecTrustRef within the SecContextRef, then SecTrustSetAnchorCertificates() would do the job. Unfortunately, this avenue only led me to SSLGetPeerSecTrust() which seems to be an Apple-private API.

xcode when i run program on iphone 6 screen looks iphone 5 How to fix this?

I have a problem with an app that i created, it's developed based on a 4 inch layout, a week ago i've tested it on Iphone 6 Simulator it looked great, today when i wanted to take screenshots, the screen looks like iphone 5 screen. I've checked and unchecked AutoLayout, and size classes was disabled from the begging.

Anyone had this issue?

custom keyboard app extension not appearing in Xcode

So, I've been researching the realm of custom keyboards and I was about to get started. Then, once I opened Xcode, I naturally looked for the "Custom Keyboard" template under "Application Extension". This template option can be seen in a screen shot in a custom keyboard tutorial by WeLoveSwift (http://ift.tt/1GXLn52). I realize that a question like this (if not exactly) has been asked (Extension project templates not appearing in Xcode 6) here. Sadly, I don't really understand the answer/it doesn't help.

Thanks very much and thanks a load in advance!

Filter PHAssetCollections within radius of CLLocationCoordinate2d

I'm using the Photos framework (aka PhotoKit). In my app I need to gather Moments (which are of type PHAssetCollection). PHAssetCollection has CLLocation *approximateLocation.

However I cannot get the NSPredicate to work.

-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"approximateLocation.coordinate.latitude < 37.0"];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];

        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

The debugger will stop on

self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

with the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: approximateLocation.coordinate.latitude < 37'

This seems strange since I can use NSPredicate to filter by startDate or endDate.

Anyhow, next I thought I'd try the NSPredicate with block:

-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            // Logic goes here
            return YES;
        }];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

Again the debugger stops at

self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

with a different error message:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: BLOCKPREDICATE(0x27d338)'

Finally I remembered reading in CloudKit documentation that they added a new support for filtering by distance. However this is for CKQuery, not NSPredicate. I decided to give it a try anyhow. I use my coordinate to make a CLLocation then call:

-(void)getMomentsNearLocation:(CLLocation*)location completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"distanceToLocation:fromLocation:(%K,%@) < %f",
                             location,
                             2.0];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

You guessed it. Error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CLLocation rangeOfString:]: unrecognized selector sent to instance 0x19e3e350'

In the mean time I'll just iterate through the list of PHAssetCollections and manually calculate if it's near the CLLocation. This will be far less efficient.

NSTimer starts, stops, and continues after window closes

So here is what's happening in human logic (but not suppose to be).

  1. My View controller loads
  2. retrieves my images from Parse successfully
  3. sets the first retrieved image equal to my UIImageView image
  4. starts my timer of 5 Seconds (I think)
  5. And then it doesn't do anything, just remains on the very first image
  6. Once I close the window (which was presented modally by previous view controller), I see in the console my println() outputs and my timer begins to work.

The GOAL: To present an image in my UIImageView for 5 seconds or so, and then display the next one in line (imageArray).

Is it my timer that's causing this pause in function, or does it have something to do with how my code is arranged? All suggestions/help are very much appreciated as this is a very frustrating issue.

This is in Swift language, but I can read Objective-C.

Here is my code for the class:

//
//  ImageDisplayViewController.swift
//  
//
//  Created by on 5/3/15.
//
//

import Cocoa
import ParseOSX

class ImageDisplayViewController: NSViewController {


@IBOutlet weak var imageView: NSImageView!

var venue: String!
var imageArray = [(Int, NSImage)]()
var image: NSImage!
var timeToDisplay: Int = 0

var timer = NSTimer()

override func viewDidLoad() {
    super.viewDidLoad()

    venue = "Bees"
    loadImages()


}

var k: Int = 0

func presentNextImage() {
    if(k<imageArray.count) {
    imageView.image = imageArray[k].1
    timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("presentNextImage"), userInfo: nil, repeats: false)
        println(timer.timeInterval)
        //imageView.image = imageArray[k].1
        println("k is \(k)")
        k++
        println("Just set a new imageView.image")
    } else {
        println("K is n longer <imageArray.count")
    }
}



func loadImages() {
    var query = PFQuery(className:groupz)
    query.whereKeyExists("imageFile")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {
            println("Successfully retrieved \(objects!.count) objects.")
            // Do something with the found objects
            if let objects = objects as? [PFObject] {
                for object in objects {
                    let thumbNail = object["imageFile"] as! PFFile
                    self.image = NSImage(data: thumbNail.getData()!)
                    let time: AnyObject? = object["displayTime"]
                    self.timeToDisplay = time!.integerValue

                    let tempTuple = (self.timeToDisplay, self.image!)
                    self.imageArray.append(tempTuple)

                }
            }
            println("imageArray.count is: \(self.imageArray.count)")
            self.presentNextImage()
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
    }
}

}

Swift: obejcts as array

I'm new in Swift and I got problem using an array of objects.

class myClass {
    var test: Int?

    static func testFunc() {
        var array = [myClass] (count: 30, repeatedValue: myClass())
        for i in 0...20 {
            array[i].test = i*2
        }

        for a in 0...20 {
            println(array[a].test)
        }
    }
}

I really have no idea what could be wrong here but my result is always 40 instead of 0 to 40:

Optional(40)
Optional(40)
Optional(40)
ect......

Does anyone know how to solve this problem? Almost seems a bit like a bug.

Regards Nils

Unable to access kABPersonNoteProperty

I have the following code which copies data from the iPhone's contacts into an NSMutableDictionary. I'm using optional binding as discussed in this answer.

The firstName and lastName fields copy properly (as well as phone and email fields not shown here), but I have never been able to access the kABPersonNoteProperty, nor have I seen the println statement in the log. I've tried to copy the note as both String and NSString without success. Any ideas what could be causing this problem?

var contactInfoDict:NSMutableDictionary!

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) {

    self.contactInfoDict = ["firstName":"", "lastName":"", "notes":""]

    if let firstName:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(firstName, forKey: "firstName")
        println(firstName)
    }

    if let lastName:String = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(lastName, forKey: "lastName")
        println(lastName)
    }

    if let notes:String = ABRecordCopyValue(person, kABPersonNoteProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(notes, forKey: "notes")
        println("Note: \(notes)")
    }

}

Edit Here is the full class:

import UIKit
import AddressBookUI

class ContactsVC: UIViewController, ABPeoplePickerNavigationControllerDelegate {

@IBOutlet weak var done_Btn: UIBarButtonItem!
@IBAction func dismissContacts(sender: UIBarButtonItem) {
    self.dismissViewControllerAnimated(true, completion: nil)
    println("ContactsVC dismissed")
}

@IBOutlet weak var viewContainer: UIView!

var object:PFObject = PFObject(className: "Contact")
let personPicker: ABPeoplePickerNavigationController
var contactInfoDict:NSMutableDictionary!

required init(coder aDecoder: NSCoder) {
    personPicker = ABPeoplePickerNavigationController()
    super.init(coder: aDecoder)
    personPicker.peoplePickerDelegate = self
}

override func viewDidLoad() {
    super.viewDidLoad()

    done_Btn.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir Next Medium", size: 16)!], forState: UIControlState.Normal)

}


@IBAction func addContact() {

    let actionSheetController: UIAlertController = UIAlertController(title: nil, message: "Would you like to select a contact from your iPhone or create a new contact directly in the app?", preferredStyle: .ActionSheet)

    let selectContactAction: UIAlertAction = UIAlertAction(title: "Select from iPhone", style: .Default) { action -> Void in
        self.performPickPerson(UIAlertAction)
    }
    actionSheetController.addAction(selectContactAction)

    let createContactAction: UIAlertAction = UIAlertAction(title: "Create App Contact", style: .Default) { action -> Void in
        self.performSegueWithIdentifier("AddContact", sender: self)
    }
    actionSheetController.addAction(createContactAction)

    let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) {
        action -> Void in
    }
    actionSheetController.addAction(cancelAction)

    self.presentViewController(actionSheetController, animated: true, completion: nil)
}


func performPickPerson(sender : AnyObject) {
    self.presentViewController(personPicker, animated: true, completion: nil)
}


func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController!) {
    personPicker.dismissViewControllerAnimated(true, completion: nil)
}

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) {

    self.contactInfoDict = ["firstName":"", "lastName":"", "company":"", "mobilePhone":"", "homePhone":"", "workPhone":"", "personalEmail":"", "workEmail":"", "street":"", "city":"", "state":"", "zipCode":"", "notes":""]

    if let firstName:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(firstName, forKey: "firstName")
        println(firstName)
    }

    if let lastName:String = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(lastName, forKey: "lastName")
        println(lastName)
    }

    if let company:String = ABRecordCopyValue(person, kABPersonOrganizationProperty)?.takeRetainedValue() as? String {
        contactInfoDict.setObject(company, forKey: "company")
        println(company)
    }


    if let phonesRef:ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty)?.takeRetainedValue() as ABMultiValueRef? {
        for (var i = 0; i < ABMultiValueGetCount(phonesRef); i++ ) {
            var currentPhoneLabel:CFStringRef = ABMultiValueCopyLabelAtIndex(phonesRef, i).takeRetainedValue()
            var currentPhoneValue:CFStringRef = ABMultiValueCopyValueAtIndex(phonesRef, i)?.takeRetainedValue() as! CFStringRef

            if let mobileResult = CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, CFStringCompareFlags.CompareCaseInsensitive) as CFComparisonResult? {
                if mobileResult == CFComparisonResult.CompareEqualTo {
                    contactInfoDict.setObject(currentPhoneValue, forKey: "mobilePhone")
                }
            }

            if let homeResult = CFStringCompare(currentPhoneLabel, kABHomeLabel, CFStringCompareFlags.CompareCaseInsensitive) as CFComparisonResult? {
                if homeResult == CFComparisonResult.CompareEqualTo {
                    contactInfoDict.setObject(currentPhoneValue, forKey: "homePhone")
                }
            }
            if let workResult = CFStringCompare(currentPhoneLabel, kABWorkLabel, CFStringCompareFlags.CompareCaseInsensitive) as CFComparisonResult? {
                if workResult == CFComparisonResult.CompareEqualTo {
                    contactInfoDict.setObject(currentPhoneValue, forKey: "workPhone")
                }
            }
        }

    }

    if let emailsRef:ABMultiValueRef = ABRecordCopyValue(person, kABPersonEmailProperty)?.takeRetainedValue() as ABMultiValueRef? {
        for (var i = 0; i < ABMultiValueGetCount(emailsRef); i++ ) {
            var currentEmailLabel:CFStringRef = ABMultiValueCopyLabelAtIndex(emailsRef, i).takeRetainedValue()
            var currentEmailValue:CFStringRef = ABMultiValueCopyValueAtIndex(emailsRef, i)?.takeRetainedValue() as! CFStringRef

            if let email = kABHomeLabel as CFStringRef? {
                if let homeResult = CFStringCompare(currentEmailLabel, kABHomeLabel, CFStringCompareFlags.CompareCaseInsensitive) as CFComparisonResult? {
                    if homeResult == CFComparisonResult.CompareEqualTo {
                        contactInfoDict.setObject(currentEmailValue as String, forKey: "personalEmail")
                    }
                }
            }
            if let workResult = CFStringCompare(currentEmailLabel, kABWorkLabel, CFStringCompareFlags.CompareCaseInsensitive) as CFComparisonResult? {
                if workResult == CFComparisonResult.CompareEqualTo {
                    contactInfoDict.setObject(currentEmailValue as String, forKey: "workEmail")
                }
            }
        }
    }

    if let addressRef:ABMultiValueRef = ABRecordCopyValue(person, kABPersonAddressProperty)?.takeRetainedValue() as ABMultiValueRef? {
        if ABMultiValueGetCount(addressRef) > 0 {
            var addressDict:NSDictionary = ABMultiValueCopyValueAtIndex(addressRef, 0)?.takeRetainedValue() as! NSDictionary

            if let street = addressDict.objectForKey(kABPersonAddressStreetKey) as? String {
                contactInfoDict.setObject(street as NSString, forKey: "street")
            }

            if let city = addressDict.objectForKey(kABPersonAddressCityKey) as? String {
                contactInfoDict.setObject(city as NSString, forKey: "city")
            }

            if let state = addressDict.objectForKey(kABPersonAddressStateKey) as? String {
                contactInfoDict.setObject(state as NSString, forKey: "state")
            }

            if let zipCode = addressDict.objectForKey(kABPersonAddressZIPKey) as? String {
                contactInfoDict.setObject(zipCode as NSString, forKey: "zipCode")
            }
        }
    }

    // Notes is not currently accessible
    if let note:String = ABRecordCopyValue(person, kABPersonNoteProperty)?.takeRetainedValue() as? String {
        println("12")
        contactInfoDict.setObject(note, forKey: "notes")
        println("Note: \(note)")
    }

    saveToContact()
}

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, shouldContinueAfterSelectingPerson person: ABRecord!, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool {
    return false
}


func saveToContact(){
    self.object["username"] = PFUser.currentUser()!

    if let firstName = contactInfoDict["firstName"] as? String{
        self.object["contactFirstName"] = firstName
    }

    if let lastName = contactInfoDict["lastName"] as? String{
        self.object["contactLastName"] = lastName
    }

    if let company = contactInfoDict["company"] as? String{
        self.object["contactCompany"] = company
    }

    if let mobilePhone = contactInfoDict["mobilePhone"] as? String{
        self.object["contactMobilePhone"] = mobilePhone
    }

    if let homePhone = contactInfoDict["homePhone"] as? String{
        self.object["contactHomePhone"] = homePhone
    }

    if let workPhone = contactInfoDict["workPhone"] as? String{
        self.object["contactWorkPhone"] = workPhone
    }

    if let personalEmail = contactInfoDict["personalEmail"] as? String{
        self.object["contactPersonalEmail"] = personalEmail
    }

    if let workEmail = contactInfoDict["workEmail"] as? String{
        self.object["contactWorkEmail"] = workEmail
    }

    if let street = contactInfoDict["street"] as? String{
        self.object["contactStreet"] = street
    }

    if let city = contactInfoDict["city"] as? String{
        self.object["contactCity"] = city
    }

    if let state = contactInfoDict["state"] as? String{
        self.object["contactState"] = state
    }

    if let zipCode = contactInfoDict["zipCode"] as? String{
        self.object["contactZipCode"] = zipCode
    }

    if let notes = contactInfoDict["notes"] as? String{
        self.object["contactNotes"] = notes
    }

    self.object["contactType"] = "Lead"

    self.object["contactIsActive"] = true


    var addrObject = self.object
    self.object.pinInBackgroundWithName("Contacts")
    self.object.saveEventually{ (success, error) -> Void in
        if (error == nil) {
            println("saved in background")
        } else {
            println(error!.userInfo)
        }
    }
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

Pixelated circles when scaling with SKSpriteNode

The perimeter around a circle gets pixelated when scaling down the image.

The embedded circle image has a radius of 100 pixels. (The circle is white so click around the blank space, and you'll get the image.) Scaling down using SpriteKit causes the border to get very blurry and pixelated. How to scale up/down and preserve sharp borders in SpriteKit? The goal is to use a base image for a circle and create circle images of different sizes with this one base image.

White circle

    // Create dot
    let dot = SKSpriteNode(imageNamed: "dot50")

    // Position dot
    dot.position = scenePoint

    // Size dot
    let scale = radius / MasterDotRadius
    println("Dot size and scale: \(radius) and \(scale)")
    dot.setScale(scale)

    dot.texture!.filteringMode = .Nearest

Swift Line Command : xcrun swiftc

I'm using the swift line command to comiple my code Client.Swift . when i compile i'm getting the object Client.o

Now, i would to link the Client .o with my static library libjjeromqi386.a in order to generate the excutable app. To do this i enter this line command :

$ xcrun swiftc -sdk /Applications/http://ift.tt/1CYBL8H -o app Client.o -target i386-apple-ios8.3 -import-objc-header /Users/systems/pMaster/ProjetXcode/SimpleSwift/Bridging-Header.h -L/Users/systems/pMaster/ProjetXcode/Librairies -Xcc -I/Users/systems/pMaster/ProjetXcode/j2objc-0.9.6/include -Xcc -I/Users/systems/pMaster/ProjetXcode/jjeromqObjC/src/main -Xcc -I/Applications/http://ift.tt/J1t0CJ

i get the error :

Undefined symbols for architecture i386: "_OBJC_CLASS_$_OrgZeromqZMQ", referenced from: __TMaCSo12OrgZeromqZMQ in Client.o "_OBJC_CLASS_$_OrgZeromqZMQ_Context", referenced from: __TMaCSo20OrgZeromqZMQ_Context in Client.o "_OBJC_CLASS_$_OrgZeromqZMQ_Socket", referenced from: __TMaCSo19OrgZeromqZMQ_Socket in Client.o "_OrgZeromqZMQ_contextWithInt_", referenced from: __TFC6Client4main6ClientfS0_FT_T_ in Client.o ld: symbol(s) not found for architecture i386

Any help please ?

You should know that the library libjjeromqi386 is i386 architecture, as the client.o too

Thanks in advance

UICollectionViewCell change cell size while scrolling

I'm trying to create a UICollectionView where the UICollectionViewCell is getting scaled down when "leaving" the visible area at the top or bottom. And getting scaled up to normal size while "entering" the visible area.

I've been trying some scale/animation code in: scrollViewDidScroll() , but I can't seem to get it right.

My complete function looks like this:

 func scrollViewDidScroll(scrollView: UIScrollView) {

    var arr = colView.indexPathsForVisibleItems()

    for indexPath in arr{

        var cell = colView.cellForItemAtIndexPath(indexPath as! NSIndexPath)!
        var pos = colView.convertRect(cell.frame, toView: self.view)

        if pos.origin.y < 50 && pos.origin.y >= 0{

            cell.hidden = false

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(0.02 * pos.origin.y, 0.02 * pos.origin.y)

            })

        }else if pos.origin.y == 50{

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(1, 1)
            })

        }
    }
}

Is this in some way the right approach, or is there another better way?