vendredi 31 juillet 2015

How can I make a 2d platformer character controller in Sprite Kit? (Xcode 6)

I've asked a few times but haven't really found what I'm looking for. I need a simple character controller that allows my character to continuously move left if the left side of the screen is held and right side as well. When let go I would like the character to stop moving.

My GameScene.swift file:

import SpriteKit


class GameScene: SKScene, SKPhysicsContactDelegate {

let character = SKSpriteNode(texture: SKTexture(imageNamed: "character"))
var move = false

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    //world
    self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -5.0)
    self.physicsWorld.contactDelegate = self
    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)


    //character
    character.position = CGPointMake(self.frame.size.width * 0.6, self.frame.size.height * 0.6)
    character.setScale(0.2)
    character.physicsBody = SKPhysicsBody(rectangleOfSize: character.size)
    character.physicsBody?.dynamic = true
    character.physicsBody?.allowsRotation = false
    self.addChild(character)
    character.physicsBody?.affectedByGravity = true




    //platform 1
    var platform = SKSpriteNode(texture: SKTexture(imageNamed: "platform"))
    platform.position = CGPointMake(self.frame.size.width * 0.6, CGRectGetMidY(self.frame))
    platform.physicsBody = SKPhysicsBody(rectangleOfSize: platform.size)
    platform.physicsBody?.dynamic = false
    platform.setScale(0.25)
    platform.physicsBody?.friction = 1
    platform.physicsBody?.restitution = 0
    platform.physicsBody?.linearDamping = 0
    self.addChild(platform)

    //platform 2
    var platformTexture2 = SKTexture(imageNamed: "platform")
    var platform2 = SKSpriteNode(texture: platformTexture2)
    platform2.position = CGPointMake(self.frame.size.width * 0.4, self.frame.size.height * 0.3)
    platform2.physicsBody = SKPhysicsBody(rectangleOfSize: platform2.size)
    platform2.physicsBody?.dynamic = false
    platform2.setScale(0.25)
    platform2.physicsBody?.friction = 1
    platform2.physicsBody?.restitution = 0
    platform2.physicsBody?.linearDamping = 0
    self.addChild(platform2)


    //platform main
    var platformTexture3 = SKTexture(imageNamed: "platform")
    var platform3 = SKSpriteNode(texture: platformTexture2)
    platform3.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame) + platform3.size.height / 3)
    platform3.physicsBody = SKPhysicsBody(rectangleOfSize: platform3.size)
    platform3.physicsBody?.dynamic = false
    platform3.setScale(1)
    platform3.size.width = platform3.size.width * CGFloat(2.0)
    platform3.physicsBody?.friction = 1
    platform3.physicsBody?.restitution = 0
    platform3.physicsBody?.linearDamping = 0
    self.addChild(platform3)

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */


    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if location.x < CGRectGetMidX(self.frame){
            character.physicsBody?.applyImpulse(CGVector(dx: -50, dy: 0))
        } else if location.x > CGRectGetMidX(self.frame){
            character.physicsBody?.applyImpulse(CGVector(dx: 50, dy: 0))
        }
    }



    func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        character.physicsBody?.velocity = CGVector(dx: 0, dy: 0)


    }




    func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */


    }
};
}

Search table view using multiple filters

I would like to ask how can I search with multiple filters in searchDisplayController

here is my method:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    // Filter the array using the filter method
    self.filteredCandies = self.person.filter({( candy: Candy) -> Bool in

        let categoryMatch = (scope == "All") || (candy.category == scope)

        let stringMatch = candy.name.rangeOfString(searchText)

        return categoryMatch && (stringMatch != nil)

Accessing location variable outside of locationmanager func?

class EditProfileViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, UITextViewDelegate {

var manager:CLLocationManager = CLLocationManager()

override func viewDidLoad() {
        super.viewDidLoad()

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        if iOS8 {
            manager.requestWhenInUseAuthorization()
        }

        manager.startUpdatingLocation()
        aboutText.delegate = self
    }

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if locations.count > 0 {
            self.manager.stopUpdatingLocation()
            let location = locations[0] as! CLLocation
            var currentLocation = PFGeoPoint(location: location)
        }
    }

    @IBAction func singlecomparepost(sender: AnyObject) {
post["location"] = currentLocation
post.saveInBackground()
}

Thats how my code is but i cant access "currentLocation" at the singlecomparepost function.Is there a way to set the location as a variable for the whole view controller?

'UIImageView+AFNetworking.h' file not found

I'm learning Objective C and doing some practice iOS following some tutorial. They quickly mention the use of AFNetworking and how to use it however after hours of frustration and roaming the internet I can not get it to work. I've included the AFNetworking files and #import "AFNetworking.h" works but #import "UIImageView+AFNetworking.h" gives the error

'UIImageView+AFNetworking.h' file not found

What could I be doing wrong? The tutorial i'm following might be outdated. I've simply downloaded the latest version from github, then in Xcode via File>Add Files I added the folder containing the files (I used the "Copy items if needed" and "Create groups" options).

I've attached a picture. Maybe that can give some clarification. enter image description here

iOS Constraints Way off On Device Only

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

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

Any debugging suggestions?

Not able to reload data properly when retrieving objects from Parse

I am retrieving data from "_User" class this way:

my declarations ..

 var userIds = [userListTableViewCell]()
 var userNames = [String]()
 var profilePics = [PFFile]()
 var gender = [String]()


var userQuery = PFUser.query()
        userQuery?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

            if let objects = objects {

                self.userIds.removeAll(keepCapacity: true)
                self.userNames.removeAll(keepCapacity: true)
                self.profilePics.removeAll(keepCapacity: true)

                for object in objects {

                    if let user = object as? PFUser {
                        if user.objectId != PFUser.currentUser()?.objectId {

                            self.userIds.append(object["objectId"] as! userListTableViewCell)  // getting an error here..  "unexpectedly found nil while unwrapping an Optional value"
                            self.userNames.append(object["fullName"] as! String!)
                            self.profilePics.append(object["profilePicture"] as! PFFile!)
                            self.gender.append(object["gender"] as! String!)

                        }


                    }
                    self.tableView.reloadData()
                }


            }




        })

screen shots of my app[![][1]]1

here when i click on follow button for user "Rfdfbd" then automatically the "unfollow" title appears on user "Ihbj....." also :/ how can i fix this??

Screen Shots of my app..

my IBAction followButton code is here:

@IBAction func followButtonTapped(sender: UIButton) {

    println(sender.tag)

    sender.setTitle("unfollow", forState: UIControlState.Normal)

    let getOjbectByIdQuery = PFUser.query()
    getOjbectByIdQuery!.whereKey("objectId", equalTo: userIds[sender.tag])
    getOjbectByIdQuery!.getFirstObjectInBackgroundWithBlock { (foundObject: PFObject?, error: NSError?) -> Void in

        if let object = foundObject {

            var followers:PFObject = PFObject(className: "Followers")
            followers["user"] = object
            followers["follower"] = PFUser.currentUser()
            followers.saveEventually()

        }
    }
}

I am using sender.tag for the follow button here..

UITextView height based on content text in UiTableView Cell

I try several time to make textview inside tableview cell to be sized height based on text inside textview. I tried the following with no luck:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TnCityFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityFeedCell" forIndexPath:indexPath];

    cell.FeedMainText.text = [[self.FeedArray valueForKey:@"FEED_MAIN_TEXT"] objectAtIndex:indexPath.row];


    CGSize size = [cell.FeedMainText systemLayoutSizeFittingSize:cell.FeedMainText.contentSize];
    CGRect frame = cell.FeedMainText.frame;
    frame.size.height = size.height;
    cell.FeedMainText.frame = frame;

    return cell;
}

I hope to find some way to solve this

Thanks :)

Rounding edge on UITextField

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

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

http://ift.tt/1Izbt0O

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

Please help.

How can I create an iOS webapp that returns to the previous state after being inactive?

When I create an iOS webapp in HTML, I use following code:

<meta name="apple-mobile-web-app-capable" content="yes" />

So, after adding it as a Safari bookmark to the home screen of the iPhone and starting it, I noticed that once I go back to the home screen and re-open the app, the web app doesn't keep its previous state.

It doesn't start where I left of and opens the start page instead. Native apps don't do that.

How can I create an iOS webapp that returns to the previous state after being inactive?

Analytics in iOS App - Request user consent

I'm debating whether to include (Google) analytics in my iOS app. Obviously I would like the analytics data, but my concern is whether to simple advise the user that data is being collected, or to specifically request their consent.

Is specific consent required, or can one simple inform the user via a loading page or website privacy policy page? Apple has a rule on consent, but does this necessarily translate into displaying a dialogue box with a Agree/Disagree buttons?

Thanks!

Application Loader Error ITMS-90035 Invalid Signature after publishing app in flash pro CC

All of my apps created in flash pro CC currently are being rejected by application loader with the error

ITMS-90035 Invalid Signature

All my certificates and provisioning profiles have been recreated several times and I continue to get the error, any fix on this?

Special characters showing bold in UILabel

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

Here is what it's looking like:

enter image description here

React Native: Cannot read property 'push' of undefined - Have NavigatorIOS and ES6 bind(this)

I am developing a react native application and I am attempting to route the user to the next view after successfully logging in through Facebook.

The problem is that I continue to get an error stating "Cannot read property 'push' of undefined." I have checked all the related answers on the forum and I have made sure to include NavigatorIOS and bind(this) on my function call - so those are the issue.

I would love assistance in determining what is wrong, as I am a novice dev.

Here is the error:

Error: Cannot read property 'push' of undefined
 stack: 
  <unknown>                                              index.ios.bundle:1498
  MessageQueue.__invokeCallback                          index.ios.bundle:7235
  <unknown>                                              index.ios.bundle:7151
  guard                                                  index.ios.bundle:7104
  <unknown>                                              index.ios.bundle:7151
  <unknown>                                              index.ios.bundle:7148
  ReactDefaultBatchingStrategyTransaction.Mixin.perform  index.ios.bundle:6552
  Object.ReactDefaultBatchingStrategy.batchedUpdates     index.ios.bundle:15885
  Object.batchedUpdates                                  index.ios.bundle:5084
 URL: undefined
 line: undefined
 message: Cannot read property 'push' of undefined

============================

Here is my code

'use strict';

var React = require('react-native');
var Main = require('./App/Components/Main');
var Icon = require('./node_modules/react-native-vector-icons/FontAwesome');
var FacebookLoginManager = require('NativeModules').FacebookLoginManager;
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
NavigatorIOS,
Navigator,
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
 welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
 instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
    marginTop: 10
 },
 icon: {
    fontSize: 20,
    color: 'white',
    paddingVertical: 5,
    paddingHorizontal: 8,
    borderRadius: 4,
    backgroundColor: '#3b5998',
 },
text: {
    marginLeft: 10,
    color: 'white',
    fontWeight: '600',
},
});

class nomsyapp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      result: 'Find the Foods that Fit Your Lifestyle',
      loggedIn: false,
    };
  }

  login() {
    FacebookLoginManager.newSession((error, info) => {
      if (error) {
        this.setState({result: error});
      } else {
        this.setState({result: info});
        this.setState({loggedIn: true});
        this.props.navigator.push({
          component: Main,
          title: 'Choose Your Lifestyle',
        });
      }
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableHighlight onPress={this.login.bind(this)}>
         <Icon name="facebook" style={styles.icon}>
            <Text style={styles.text}>Login with Facebook</Text>
          </Icon>
        </TouchableHighlight>
        <Text style={styles.instructions}>
          {this.state.result}
        </Text>
      </View>
    );
  }
};


AppRegistry.registerComponent('nomsyapp', () => nomsyapp);

============================

Swift: My Convenience init does not see the normal init

I am trying to create a convenience init for my class: User. I've done this before for another class, and - to create it again - I have used the same code, just differed for my User class.

Here is my User class:

import Foundation

class User {
    //Database Variables
    let userID: String?
    let firstName: String?
    let lastName: String?
    let password: String?
    let emailID: String?
    let dob: String? //timestamp
    let picture: String? //URL?
    let location: Location?
    let sex: String?

convenience init(data: [[String: AnyObject]]) {
    self.init(userID: String(data["user_id"]!), firstName: String(data["first_name"]!), lastName: String(data["last_name"]!), password: String(data["password"]!), emailID: String(data["email"]!), dob: String(data["dob"]!), picture: String(data["picture"]!), location: Location(String(data["street"]!), String(data["city"]!), String(data["state"]!), String(data["zip"]!), String(data["country"]!)), sex: String(data["sex"]!))
}

init (userID: String, firstName: String, lastName: String, password: String, emailID: String, dob: String, picture: String, location: Location, sex: String) {
    self.userID = userID
    self.firstName = firstName
    self.lastName = lastName
    self.password = password
    self.emailID = emailID
    self.dob = dob
    self.picture = picture
    self.location = location
    self.sex = sex
}

However, Swift doesn't see the self.init method. I am getting a Could not find an overload for init that accepts the supplied arguments

What is wrong?

iOS Swift Dictionary Cloning

I have an NSMutableDictionary that I make copies of. After I make the copies I want to change the values in each dictionary independently. However, when I change one all the others change. It's almost like the copies are just pointers back to the original. My code to set them is:

var nf = text?.toInt()!
var creatureInfo = NSMutableDictionary()
for var c = 0;c<nf;c++ {
    creatureInfo = NSMutableDictionary()
    creatureInfo = getCreature(name)
    creatureInfo.setValue("creature", forKey: "combat-type")
    combatants.append(creatureInfo)
}

I thought at doing creatureInfo = NSMutableDictionary() in the loop would work but it did not.

Swift dyld: Library not loaded - using CoCoapods

I apologize for what may seem like an overly asked question, but no matter how many answers to related questions I'm asking, none of them seem to work. See (in order) here, here, here, and here.

I'm running XCode 6.4 with iOS 8 (iPhone only), using CoCoaPods. Many of other answers provided, there seems to be a build setting, or general setting that does not exist in my version of XCode, yieling many conclusions not helpful.

As a matter of reference, I followed This CocoaPod Tutorial which worked with ease. But it's only when I attempt to load the app onto my phone (yes, I have valid certificates, and my other apps work just fine without using other dependencies), the app immediately crashes just as it's about to load.

dyld: Library not loaded: @rpath/Pods_ExamplePods.framework/Pods_ExamplePods
Referenced from: /private/var/mobile/Containers/Bundle/Application/F109A377-3EA4-48C2-9042-CB6C384C9F30/http://ift.tt/1KG8T8A
Reason: image not found
(lldb) 

See here where I named my app "ExamplePods"

enter image description here

And then here is my Folder Structure, opened in Workspace mode. Note that there's only 3 dependencies.

enter image description here

Then see "General Settings" and "Build Settings"

enter image description here

enter image description here

I'm at a complete loss, help is much appreciated!

how i use the weather.com site search in my app?

i want to use weather.com search engine. i used weather forecast-weather.com and it's easy to implement in my app because the url containing the name of the city

http://ift.tt/1rAAixy

this is my code now:

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

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

        if url != nil {

            let urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(urlContent)
        }
    })

Resizing Complex UIView with AutoLayout (Swift)

So I'm pretty new to AutoLayout, but more often than not I'm able to hack my views into shape or model off samples on the web.

However, I've created this rather complex view that just doesn't resize no matter what constraints I try.

Here are a few screenshots of what's going on.

The first shot is my Interface Builder layout. It's got a 4-corners kind of thing going on, with a UIImageView in each corner. In the center is a blurred VisualEffectView; it lays on top of the images. The layout was constructed with the parent view at 200x200

The second shot is a successful rendering at 200x200. As you can see, the 4 images load fine (yeah, I know they're a bit stretched, I just haven't handled their scaling code yet). Programmatically, I set the cornerRadius properties of both the parent view and the blurred view to 1/2 their width, so as to make them circular. Also programmatically, I added a label as a subview to the blurred view.

Then it all goes downhill. The third shot is my attempting to render the view at 250x250. The parent view renders well and maintains a circular shape, but just about everything else is wrong.

The most frustrating part is the UIImageViews, which all go haywire and extend their bounds even though I've set them to be equal widths.

The blurred view at least stays centered, but something isn't called which prevents its bounds.width property to be updated, which is what the cornerRadius is based off of.

The label doesn't stay center in the blurred view, despite setting its autoesizingMask to flexible all around.

Here is a snippet of my initialization code, which might be useful.

Any help that you all could provide would be greatly appreciated (even if it just fixes one of the several issues).

P.S. I apologize for the cats pics.

Edit: I achieved the desired result by writing the code manually and ditching Interface Builder and AutoLayout entirely.

How to enter parameters for latitude longitude

I am using the Yelp API and this is the search method:

func searchWithTerm(term: String, success: (AFHTTPRequestOperation!, AnyObject!) -> Void, failure: (AFHTTPRequestOperation!, NSError!) -> Void) -> AFHTTPRequestOperation! {
        // For additional parameters, see http://ift.tt/QXVBgL
        var parameters = ["term": term, "ll": "37.77493,-122.419415"]
        return self.GET("search", parameters: parameters, success: success, failure: failure)
    }

This is currently hardcoded with the given ll parameter. I have a the user's location stored in a different VC and when i try to pass in the lat and long to replace the hardcoded values, I get errors...

What am i doing wrong? It should be rather simple to pass in a value of double...

Send local notification when download completes through NSURLSession / NSURLSessionDownloadTask

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

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

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

Load an image from an asset catalog off the main thread?

I'm trying to load an image from an asset catalog into a UIImage off of the main thread, but can't seem to find any way to do it. If the image was not in an asset catalog I would use pathForResource and imageWithContentsOfFile:

NSString *path = [[NSBundle mainBundle] pathForResource:icon ofType:nil];
if(path) {
  image = [UIImage imageWithContentsOfFile:path];
}

But pathForResource: does not work for images in asset catalogs. Is there any way to do this without having to go to the main thread to load the image? Im guessing the answer is no.

What won't work:

  • Manually creating the path for the image based on the main bundle path. I have images in multiple asset catalogs, and asset catalogs can be compiled in a binary form.
  • [UIImage imageNamed:] is not thread safe, and can not be used off the main thread. The docs have said it's not thread safe for at least the last several major releases of iOS, and starting in iOS 8 it really does crash when used off the main thread.

What i'm doing now:

dispatch_sync(dispatch_get_main_queue(), ^{
  image = [UIImage imageNamed:icon];
});

Implement *find* friends in parse.com

There are multiple examples on the net to implement friend/follower relationships between users. But I am unable to find a clever solution to search for the friends. Every example assumes that I selected the user objects already but it has no example how to find them prior to that.

Given an application that allows ad-hoc registration, combined with facebook/twitter login what would be the search criteria? Username does not work because finding a user registered with facebook is not possible as facebook logins won't have a usable and easy to remember username. Natural name will lead to too many "John Smiths" so I do not like the idea again. Email address sounds reasonable (as it can be extracted from facebook profile and we can ask email verification for ad-hoc registrations) but with that I have a bit of security concerns: is there a risk that someone reads the whole database storing the email addresses? Also how do I store those addresses? Do I store them in a separate class with a pointer to the user object? But then how do I prevent the "hackers" from reading the whole list?

Will apple reject apps built with xcode 5.1

I just want to know that will apple reject app build with xcode5.1 since i ready that you need xcode6 after 1st june , but the apple documentation says you need apps built with 64bit arch and ios8 , and xcode 5.1 has both so it will be accepted ? i just want to know if i am correct .

Swift: My custom UITableViewDataSource class thinks it doesn't conform to protocol 'UITableViewDataSource'

I have checked a few other questions out there, of which the answers seem to be in the datasource methods' declarations. However, I cannot find what's wrong with my methods declarations.

Here is my class:

import UIKit

class GuestControl: UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var leftTable: UITableView!
    @IBOutlet weak var rightTable: UITableView!
    var userList = [User]() //even numbers including 0 go on the left table, odd numbers go on the

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //Here is where we link to that user's contact page
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: GuestTableViewCell = tableView.dequeueReusableCellWithIdentifier("guestCell") as! GuestTableViewCell

    if tableView == leftTable {
        cell.configureCellWithUser(userList[indexPath.row+indexPath.row])
    } else {
        cell.configureCellWithUser(userList[indexPath.row+indexPath.row+1])
    }

    return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let num = Double(userList.count) / 2.0
    if tableView == leftTable {
        return Int(round(num)) //round up
    } else {
        return Int(num) //round down
    }
}

}

And here is the exact error:

Protocol requires function 'tableView(_:numberOfRowsInSection:)' with type '(UITableView, numberOfRowsInSection: Int) -> Int'
Candidate is not '@objc', but protocol requires it
Protocol requires function 'tableView(_:cellForRowAtIndexPath:)' with type '(UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell'
Candidate is not '@objc', but protocol requires it

What is wrong?

How to detect if the image of UIImageView has changed

I have an app where the user can choose an image from the camera roll and than that image is loaded into an UIImageView. However, if the image is big there is a delay till the selected image actually appears in the UIImageView (Setting the image is not performed on the main thread so the UI does not get frozen). Until the image is set, I would like to show an activity indicator which notifies the user that the app did not freeze, its just loading the image. However I don't know how to detect when the image got set in the UIImageView to hide the activity indicator. I am guessing maybe KVO could help here, but I am not sure how to implement it properly.

Sorry for the noob question! :)

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

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

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

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

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

return instance;

And making my API calls like this:

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

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

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

Does PHImageManager return images in pixel or point size for 2x and 3x screens?

I'm loading images from the camera roll via PHImageManager, but the returned images are not retina resolution. Do I have to provide a multiplier myself for 2x and 3x or do I have something wrong?

Here is my code:

class ReviewableImageView: UIImageView {

    ...unrelated code

    imageRequestOptions = PHImageRequestOptions()
    imageRequestOptions.deliveryMode = .HighQualityFormat
    imageRequestOptions.resizeMode = .Exact

    ...unrelated code

    self.contentMode = .ScaleAspectFit
    self.backgroundColor = UIColor.clearColor()
    self.userInteractionEnabled = true

    ... unrelated code

    func reloadImage(){
        let imageManager = PHCachingImageManager()//PHImageManager()

        imageManager.requestImageForAsset(self.imageAsset,
            targetSize: self.frame.size,
            contentMode: .AspectFit,
            options: imageRequestOptions,
            resultHandler: { (image: UIImage!, info: [NSObject : AnyObject]!) in
                self.image = image
        })
    }

}

Centralized vs decentralized mobile application portals

Lately I've been reading this article about mobile app development. On page 25 / page 28 they talk about centralized and decentralized mobile application portals. Unfortunately, the article is very dated.

Let's say I want to categorize the main mobile platforms nowadays. Initially I would come up with something like this:

  • Google Android: centralized
  • Apple iOS: centralized
  • Windows Phone: centralized
  • BlackBerry OS: centralized
  • Firefox OS: decentralized
  • Amazon Fire OS: centralized

How would you complete this? I didn't find a way to validate these information. Google i.e. should be centralized because of the Google Play Store. However, there are alternative ways to download Android Apps like Aptoide. And then there is the Opera Mobile Store. You can download apps there for every platform. What does this mean for the categorization of mobile application portals?

Update: I'm still looking for some answers since I didn't figure out yet how to validate the information above. Any help is appreciated!

Update 2: After doing some further research, I was able to complete the list above. However, I'm still not sure if this really is correct. I added some bounty for those interested in reading the article and helping at my problem. Thanks.

How to check if AVPlayerViewController fast forward control has been pressed?

I have an AVPlayerViewController and AVPlayer that shows default controls. When the player is in fullscreen the >>| button acts as a fast forward but i would like to override/delegate this to act as a next button and call my playNextVideo() method. Is this at all possible, or do I have to live with the fast forwarding?

iOS Access Local Data Storage

Is there a way to create an app which generates data and then access that data on a computer from the iOS device?

I'm developing an iOS app which collects data from external devices and I need to be able to access that data through my computer. What I'm looking to do is run the iPad app and collect data. Then offload the data onto my computer to analyze through excel.

Saving TextView contents in TableView

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

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

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

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

My code:

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

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

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

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

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

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

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

Modifying layer properties for contents of collection view cell

I'm having mixed results when modifying the layer properties of an UIImageView. In a UICollectionView, I have UICollectionViewCells that have a single UIImageView in them. I want those images to look like circles, thus, in my UICollectionViewCell subclass, I override layoutSubviews and placed my code there, like so:

override func layoutSubviews() {
  super.layoutSubviews()
  image.layer.cornerRadius = CGRectGetWidth(image.bounds) / 2
  image.layer.masksToBounds = true
}

However, I was getting unreliable results. Sometimes, the images are perfect circles (as intended), but sometimes they're squares with rounded edges, that may or may not become circles if you scroll through the collectionView.

Where is the best place to put this code?

Add more native ads to existing facebook scroll ios

I am trying to add more native ads to existing scroll in ios.

FBNativeAdsManager *manager = [[FBNativeAdsManager alloc] 
initWithPlacementID:@"Placement ID" forNumAdsRequested:5];

On initialising I put the 5 to load five ads. But, If user is scrolling through those ads, I want to lazy load more ads and add them to the same scroller.

The class FBNativeAdDelegate is used as a delegate of the scroll view. as mentioned on the link http://ift.tt/1dNKlz5 It contains a delegate which tells that user has scrolled till end.

- (void)nativeAdWillLogImpression:(FBNativeAd *)nativeAd{}

The above method gets called every time when a fresh ad appears on the screen. So I know if this method gets called fifth time, I have to load more ads to it.

But, how to add more ads to it?

Any relevant help and suggestions appreciated. Cheers!

Core Data update locations for positions in background cause blocking UI

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

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    ...
}

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

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

    // Update Cell
    [cell setValuesByOpenPositionCD:position];

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

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

    if ([openPosition hasAddress]) {
        return;
    }

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

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

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

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

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

    return _managedObjectContext;
}

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

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

Convert swift arrays into JSON object

I have two arrays :

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

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

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

Any help would be very much appreciated ! Thank you !

How to add dynamic touchable objects to a TableView cell?

I am looking for a way to add different objects (40x40) to a cell so that if you touch one of these objects it will go to another screen. The only problem with this is I don't know the best way to do this as I want the table view is dynamic and i want it to change its height as more objects become available.

I think these are my options right now. Either make a collection view or somehow make it so that the table view cell is 40 x 40 and have 8 or 10 table view cells in a row depending on the phone before it starts the next row and populates that.

An example of what I am thinking is Instagrams discover page or in the new snapchat update the circles that are on the main page. Does anybody know the best way to go about this, or would a collectionView without a table be the best way to do this?

iOS NSMutableURLRequest Authorization Header

I am having trouble accessing an API call and I think it has something to do with the authorization header. I am using AlamoFire and printing out the token so I know it is valid.

var URLRequest: NSURLRequest {
    let URL = NSURL(string: Router.baseURLString + path)!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = method.rawValue

    println(Router.OAuthToken)
    if let token = Router.OAuthToken {
        mutableURLRequest.setValue("Token token=\(token)", forHTTPHeaderField: "Authorization")
    }

    println(mutableURLRequest)

    switch self {
    default:
        return mutableURLRequest
    }
}

This is what the documentation says and it works right in the terminal with the auth token:

curl -H "Authorization: Token token=<ACCESS_TOKEN>" http://ift.tt/1M1QOoI

Here is the error I'm receiving:

Optional(Error Domain=com.alamofire.error Code=-1 "The operation couldn’t be completed. (com.alamofire.error error -1.)")

After Core Data Migration Main TableView Crashes Swift

I have a fairly standard Core Data fed tableView with cell data populated from a fetchedResultsController.

Everything works as expected until I do a Core Data migration. The purpose of the lightweight migration is to provide a simple backup not to change the model. The store uses SQLite. The plan is to do the migration to generate the new data files and then to remove the new store and install the original store in order to keep the original file names.

The view for the backup procedure is also a tableView. Once the migration is completed, the new file is visible in the backup tableView. Upon clicking the "back" button to return to the original tableView, the data is visible as expected, but clicking on any row in the tableView causes an immediate crash and I'm presented with the dreaded "Object's persistent store is not reachable from this NSManagedObjectContext's coordinator" error.

I've been struggling with this for a week. I must be missing a basic concept. Any help would be appreciated. (iOS 8, Xcode 6.4)

Here are the fetchedResultsController variables. Again these work all the time until a migration is made:

var myFetchedResultsController: NSFetchedResultsController? = nil

var fetchedResultsController: NSFetchedResultsController {

    managedObjectContext = kAppDelegate.managedObjectContext

    if myFetchedResultsController != nil {
        return myFetchedResultsController!
    }//if my ! nil

    let fetchRequest = NSFetchRequest()

    let entity = NSEntityDescription.entityForName("Patient", inManagedObjectContext: managedObjectContext)
    fetchRequest.entity = entity
    fetchRequest.fetchBatchSize = 50

    //Sort keys
    let sortDescriptor = NSSortDescriptor(key: "dateEntered", ascending: false)
    let sortDescriptors = [sortDescriptor]

    fetchRequest.sortDescriptors = [sortDescriptor]

    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    var countError : NSError? = nil
    var count = managedObjectContext.countForFetchRequest(fetchRequest, error: &countError)

    println("The count is \(count)")
    //after creating a backup, this count is ALWAYS zero - never the real count

    aFetchedResultsController.delegate = self
    myFetchedResultsController = aFetchedResultsController

    var error: NSError? = nil
    if !myFetchedResultsController!.performFetch(&error) {
         // Don't forget the code to handle the error appropriately.
         println("Unresolved error \(error), \(error!.userInfo)")
        //Remove this
         abort()
    }//if !my

    return myFetchedResultsController!
}//var fetchedResultsController

The two functions for the backup procedure:

func createLocalBackupFile() {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    let theDateTime = NSDate()
    let formattedDateTime = dateFormatter.stringFromDate(theDateTime)
    let backupFileName : String = "BiopBak" + formattedDateTime + ".sqlite"
    println("backupFileName is \(backupFileName)")

    let psu : CRSPersistentStoreUtilities = CRSPersistentStoreUtilities()//the function below is in this class

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
        //println("In a background queue, creating the backup file")
        psu.backupTheStore(backupFileName)

        //go back to the main queue
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            println("Back on main queue after creating the backup file")

            if (self.backupSqlFiles.count == 1 && self.backupSqlFiles[0] == "Placeholder for empty list") {
                self.backupSqlFiles.append(backupFileName.stringByDeletingPathExtension)
                self.backupSqlFiles.removeAtIndex(0)

            } else {
                self.backupSqlFiles.append(backupFileName.stringByDeletingPathExtension)

            }//if placeholder is only record in database - else

            self.tableView.reloadData()
            println("backupSqlFiles[] = \(self.backupSqlFiles)")

        })//back to main block - inner
    })//background processing block - outer

}//createLocalBackupFile

func backupTheStore(newSQLFileName : String) -> NSPersistentStore? {

        let storeType = NSSQLiteStoreType
        var migrateError : NSError?
        var currentStore : NSPersistentStore = kAppDelegate.persistentStoreCoordinator?.persistentStores.last! as! NSPersistentStore
        let options = [NSMigratePersistentStoresAutomaticallyOption: true,
            NSInferMappingModelAutomaticallyOption: true]

        let fileManager = NSFileManager.defaultManager()
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let docsDir = paths[0] as! String
        let docsDirURL = NSURL(fileURLWithPath: docsDir)

        let originalStoreURL : NSURL = docsDirURL?.URLByAppendingPathComponent("BiopLogCloud.sqlite") as NSURL!
        var newStoreURL : NSURL = docsDirURL?.URLByAppendingPathComponent(newSQLFileName) as NSURL!

    kAppDelegate.persistentStoreCoordinator?.migratePersistentStore(currentStore, toURL: newStoreURL, options: options, withType: storeType, error: &migrateError)

    currentStore = kAppDelegate.persistentStoreCoordinator?.persistentStores.last! as! NSPersistentStore

    var removeStoreError : NSError?
    var theStores = kAppDelegate.persistentStoreCoordinator?.persistentStores

    if let theStores2 = theStores {
        for removeStore in theStores2 {
            var removed : Bool = true
            kAppDelegate.persistentStoreCoordinator?.removePersistentStore(removeStore as! NSPersistentStore, error: &removeStoreError)

            if (removeStoreError != nil) {
                println("Unable to remove persistent store \(removeStore)")
            }
        }//for in
    }//if let theStores

    var addStoreError : NSError?

    kAppDelegate.persistentStoreCoordinator?.addPersistentStoreWithType(storeType,
        configuration: nil,
        URL: originalStoreURL,
        options: options,
        error:&addStoreError)

    if (addStoreError != nil) {
        println("Unable to add persistent store \(originalStoreURL)")
        //change this to add a user alert
    }//if

    //this does not seem to do any good
    let ptvc : PatientTableViewController = PatientTableViewController()

    dispatch_async(dispatch_get_main_queue()) {
        () -> Void in
        ptvc.tableView.reloadData()
    }//block

    return thisStore

}//backupTheStore

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

I have the following setup:

enter image description here

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

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

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

Best way to make a grid of views inside a UITableViewCell

I have a UITableView which cells contains a grid-style of subviews placed in a XIB. Today they are arranged with auto-layout and constraints. These subviews may be of a dozen of types, some of these types have a fixed width, other have to fill the empty space, all have a fixed height. Each cell displays a particular set of these types based on its needs.

The image below show 3 cells with their subviews

enter image description here

The point is that architecture requires a lot of rules to updates the constraints and is not easily maintainable when a new subview type is added. Using only a XIB per cell in that case doesn't seem to be the best choice as the initial interface builder layout is just one of the multiple possible arrangement, and the cell has to do a lot of work to adapt. Also I would prefer a solution which doesn't require to touch the previous subviews types when a new one is added.

I've considered the following solutions :

  • Insert a collectionView inside the UITableViewcell, and transform the subviews to UICollectionViewCells :

    • do you think this may be a performance issue to have so much collectionViews on the screen ? (we may have up to 10 cells simultaneously on screen, each with 1 to 10 cells)
    • Considering the UICollectionViewCells would not even ever scroll inside the UITableViewCell isn't that a little overload to use a collectionView in that case, just for arranging a set of views ?
  • Use the new UIStackView

    • the stackView is only compatible with iOS 9 so this means we have to maintain 2 versions of the code for a while
    • the stackView seems to be a little complicated to place each subview pixel perfect
  • Make an individual XIB for each subview type and make the corresponding UIView to compute its own constraints based on its neighbours, making thus a custom grid system

    • this is a little bit too a "custom" solution, therefore more difficult to maintain and understand for other developers
    • it still requires to make a lot of changes if in the futur it will be a fourth column of subviews for example (= it's not a real grid system which would adapt nicely)

Which solution would you use ? Do you have other suggestions ? Thanks

Could not find add listener in PubNub in swift

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

http://ift.tt/1JA4JkO

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

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

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

CoreData asynchronous fetch causes concurrency debugger error

I'm using the

-com.apple.CoreData.ConcurrencyDebug

argument on launch to debug concurrency in my CoreData app.

During app launch, I perform an asynchronous fetch on the main thread's managed object context.

// set up the async request
   NSError * error = nil;
        [MOC executeRequest:asyncFetch error:&error];
        if (error) {
            NSLog(@"Unable to execute fetch request.");
            NSLog(@"%@, %@", error, error.localizedDescription);
        }

This code is called from the main thread, but executeRequest: enqueues it to another thread, which I understand to be the correct behavior.

The concurrency debugger doesn't like this, saying (I reckon) that I'm doing something wrong here. I've also tried wrapping this in [MOC performBlock:] which also works, but also causes a multithreading violation. In both cases I get this :

[NSManagedObjectContext __Multithreading_Violation_AllThatIsLeftToUsIsHonor__

Am I using async fetches incorrectly, or is the concurrency debugger wrong here?

EDIT : I've also tried wrapping it in MOC performBlock which should ensure that it gets called from the main thread. In any case, the call is enqueued from the main thread, but executed elsewhere.

It says the fetch has been enqueued from the main thread, but it seems to actually happen on another.

Capturing and using CKQueryCursor results using blocks?

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

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

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

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

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

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

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

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

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

Best practice for core data model object save

I have a two entity "Person" and "Car" is coming from the web service. I need to store that in sqlite through core data. I want to know what is the best approach should i bind the save method with NSmanagedobject or write differently in utility or manager?

**Approach 1** 

@interface Person : NSManagedObject

@property (nonatomic, retain) NSString * title;

- (void) saveManagedObject:(NSDictionary*)response //Responsible for init the person object and save in context

@end

**Approach 2**

@interface CoreDataUtility : NSObject

- (void) saveManagedObject:(NSDictionary*)response //Responsible for create the person object and save in context

@end

Spritekit how to add multiple .plist parameters in object call method. [self addTrampoline: CGPointFromString(level[@"trampolinePosition"])];

--> .plist file containing level parameters for trampoline object

  level3.plist file
        --Root                          Dictionary        
        ---trampoline                   Dictionary
        ----trampolineAffectedByGravity Boolean      YES
        ----trampolinePosition          String       {400,355}

--> setup method, load the .plist file but cant seem to add new parameters to call method [self addTrampoline... need to add trampolineAffectedByGravity and trampolinePosition

- (void)setupLevel:(int)levelNum
    {
        //load the plist file
        NSString *fileName = [NSString stringWithFormat:@"level%i",levelNum];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
        NSDictionary *level = [NSDictionary dictionaryWithContentsOfFile:filePath];
        [self addTrampoline: CGPointFromString(level[@"trampolinePosition"])]; 
    }

    -(void)addTrampoline:(CGPoint)pos affectedByGravity:(BOOL)affectedByGravity
    {
        trampoline = [SKSpriteNode spriteNodeWithImageNamed:@"drums0.png"];
        trampoline.position = pos;
        trampoline.name = trampolineCategoryName;
        trampoline.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:trampoline.size];
        trampoline.physicsBody.affectedByGravity = affectedByGravity;
        trampoline.physicsBody.dynamic = NO;
        trampoline.physicsBody.restitution = 1.0;
        trampoline.physicsBody.friction = 0.0;
        trampoline.physicsBody.linearDamping = 0.0;
        trampoline.physicsBody.angularDamping = 0.0;
        trampoline.physicsBody.categoryBitMask = trampolineCategory;
        trampoline.physicsBody.collisionBitMask = ballCategory;
        [_gameNode addChild:trampoline];
    }

Singleton Class and multiple asynchronous operations in Swift

I am writing an iOS Swift application that, upon startup, needs to get 2 (or more) sets of data from a server. During initialization, I must do some processing on the sets of data - kind of merging them together. And only then can I start my view controller and interact with the user. The data obtained during initialization is an array of objects that I reuse everywhere in my app.

At first, I put the code in the viewDidLoad of the view controller, but it became messy very quickly. Now, I am putting all this code inside a "singleton" class so that all my view controllers can reuse the same data. My singleton class is defined using the following code excerpt:

class Teams {
  var teams: [Team]
  static var sharedInstance = Teams()

  private init() {
    teams = []
    let queryText = "CardTypeOWSTEXT:Root"
    //The first async call (DataManager invokes the http REST to the server)
    DataManager.spSearch (queryText, success: { teamsJson -> Void in
      let json = JSON(data: teamsJson)
      ...
      // all the code to handle the data received from the server
      ...
    })
    //The second async call
    DataManager.spSocialFollowedSites ({ sitesJson -> Void in
        let json = JSON(data: sitesJson)
       ...
      // all the code to handle the data received from the server
      ...
    })

I am very new to iOS development, and I try to replicate an existing app I wrote in AngularJS. In that app, it is very simple to invoke the REST calls to the server and using promises, all I have to do is wait for both to complete to execute the matching with a statement like:

$q.all([promise1, promise2]).then(...)

but this is javascript/angular, not Swift! I know there are promises libraries (eg. PromiseKit), but I am wondering if this is the right way to do it? Would it be simpler/better with GCD? Also, does my approach using a singleton makes sense? Its purpose is to hold data shared by all the other classes, and in angular, the same concept is a factory and works quite well...

I have read many places and could not get any good guidance, so any help would be appreciated!

REFrostedViewController: Opening storyboard view controllers from AppDelegate

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

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

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

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

The usual process to open another view controller is:

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

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

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

Search table view using multiple filters

I would like to ask how can I search with multiple filters in searchDisplayController

here is my method:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    // Filter the array using the filter method
    self.filteredCandies = self.person.filter({( candy: Candy) -> Bool in

        let categoryMatch = (scope == "All") || (candy.category == scope)

        let stringMatch = candy.name.rangeOfString(searchText)

        return categoryMatch && (stringMatch != nil)

HTTPS request in iOS 9

I'm updating my app to accommodate Apple's new ATS. Without any changes to the Plist-Info,the following code throws an error at sendSynchronousRequest() in a vanilla iOS 9 simulator.

NSURL *url  =[NSURL URLWithString:@"https://Google.com"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setHTTPMethod:@"GET"];
[request setURL:url];

NSURLResponse *urlResponse = nil;
NSError *error = nil;    
NSData *reponse = [NSURLConnection sendSynchronousRequest:request
                                        returningResponse:&urlResponse
                                                    error:&error];

Error:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

Any thoughts as to what might be behind this issue?

Ps: I understand that NSURLConnection is deprecated. But this invocations works find if I add AllowArbitraryLoads in Plist.

Face visualisation and makeover iOS

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

Thanks in advance.