Affichage des articles dont le libellé est Active questions tagged ios - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged ios - Stack Overflow. Afficher tous les articles

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?