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];
}