samedi 27 juin 2015

how to make a uitableview know about where to scroll for uncreated views yet

I have a UITableView which has up to 600 items in it. They are split between headers and items (like 30 headers of 15-20 items each). It is a catalog and has to mimick the printed catalog.

There is also a navigation pop-up view that shows only the headers that a user can overlay to the main table view. It is represented like this:

header
 \subheader
header2
\subheader
  \subheader

And our code for navigating is like this:

  func tapOnMenuHeaderView(recognizer: UITapGestureRecognizer)
  {
    self.hideModalNavigation()
    self.mainTV.reloadData()
    self.mainTV.scrollToRowAtIndexPath(NSIndexPath(forRow: self.menuHeaderPositions[recognizer.view!.tag]!, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
  }

However, it doesn't go to the right place many times. It seems to always be short and gets less accurate the further down you go. Is this a limitation to scrollRowAtIndexPath and is there a way I could force a full reload or something? The only way I could get this to work was to remove using a tableview and do everything as UIViews and just increment it in a scroll view. How would I make it so that our overlay navigation scrolls to the correct place?

Add Selfie Stick Support To iOS App

I am looking to add support for a "Selfie Stick Remote" to my upcoming iOS app. This question was already asked in the form of How to detect click event of connected Bluetooth peripheral device (Selfie stick)? but for Android, not iOS.

Specifically I am looking for it to work with the bluetooth devices (like this one http://ift.tt/1NnSiqf).

randomly change image of buttons and decelerate changing

i have 2 buttons.

they are called _rightButtonPressed and _leftButtonPressed. They have an background image named "blackBackground". When they are clicked, the background image is changed to "whiteBackground".

Ok. Now i want to make a third button, that changes the background image at first _rightButtonPressed to "white", then "black", then _leftButtonPressed to "white", then "black" and so on. This change have to decelerate to the end. At least, it should be randomly stops at a button with "white" background image and click the button. I hope its comprehensible.

I have no idea, how i can do this...

How to set the title text color of UIButton?

I tried changing the colors of the text for a button, but it's still staying white.

isbeauty = UIButton()
isbeauty.setTitle("Buy", forState: UIControlState.Normal)
isbeauty.titleLabel?.textColor = UIColorFromRGB("F21B3F")
isbeauty.titleLabel!.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 25)
isbeauty.backgroundColor = UIColor.clearColor()
isbeauty.layer.cornerRadius = 5
isbeauty.layer.borderWidth = 1
isbeauty.layer.borderColor = UIColorFromRGB("F21B3F").CGColor
isbeauty.frame = CGRectMake(300, 134, 55, 26)
isbeauty.addTarget(self,action: "first:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(isbeauty)

I also tried changing it the red, black, blue, but nothing is happening.

Days countdown iOS swift

My app requires that I start countdown of days from first launch. If someone launch my app for the first time I want to count day 1 after 12 midnight (using the device clock of course) and then day2 ... and perform an action after the 21st day. It shouldn't matter if the person close the app or switch off phone. When the app come back up, it should automatically detect how many days have passed.

Does anyone have an idea how to realise that ? . I am thinking of NStimer but kind of confuse.

MagicalRecord findByAttribute returning inverse relationship documents issue

I'm having an issue figuring out how to model/fetch items with Core Data and MagicalRecord. I have two entities, User and Message, which both have inverse relationships to each other:

User Entity

Relationship    Destination    Inverse    Type
-------------------------------------------------
messages        Message        user       To Many

Message Entity

Relationship    Destination    Inverse    Type
-------------------------------------------------
user            User           messages   To One

Issue

When fetching messages by a given user, MagicalRecord is returning 2x the number of records since it's matching attributes at the user and user.messages.user keyPaths:

- (NSArray *)fetchMessagesByUser:(NSString *)identifier {

    // returning 2x the records it should
    return [Message MR_findByAttribute:@"user.identifier" withValue:identifier];
}

Should I change the way I'm using MagicalRecord or is there a fundamental issue with my Core Data model?

When programatically creating a ViewController, how can I set its view to be of type SKVIew?

I am developing a game in iOS on XCode. I have several SKScenes each associated with a UIViewController class. So in each of the view controller's viewDidLoad, I create

SKView *skView = (SKView *)self.view
SKScene * scene = [whateverSKScene sceneWithSize:skView.bounds.size]
[skView present scene]

I want to avoid the storyboard. However, when I presentViewController from the first view controller to the next, the app crashes at the line "[skView present scene]" because it thinks the new view controller's view is still UIView ('-[UIView presentScene:]: unrecognized selector sent to instance).

How can I fix this? Specifically, when creating the 2nd view controller (programatically), how can I change its view to be of type SKview not UIview? (I should note I want the scenes to be 1:1 with view controllers because almost all of them are popups like a pause-menu pop up over game play or settings pop up etc)

libssh2 iOS Error 31

I have tried several projects based on libssh2 for iOS and I consistently get error -31 when trying to upload files. The file is created on the server, but no data is uploaded. I suspect that it maybe that something is unsupported on the server as -31 is defined as LIBSSH2_ERROR_SFTP_PROTOCOL. I only have access to the server via sftp and I cannot get in touch with the admins. I can do sftp from the command line on my mac. My code is based on NMSSH. However, I have tried the demo app on DLSFTPClient with the same result.

Anyone else have a similar problem. If so, how did you correct it?

Add and save item to favorites

I have a tableview with many words and I want to add the favorites feature so each detail view can have a button to save as a Favorite. This is my code, but doesn't work, after pressing the button I get this error (property lists cannot contain objects of type 'CFType'), but if I use slovoItem.slovo or slovoItem.definice, value is saved correctly. slovoItem has values slovoItem.slovo and slovoItem.definice and I need to save completely slovoItem.

Code in my DetailViewController:

- (IBAction) addToFavorites:(id)sender
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


    NSMutableArray *tempArray = [[prefs objectForKey:@"favorite"] mutableCopy];
    favorite = tempArray;

    [favorite addObject:self.slovoItem];

    [prefs setObject:favorite forKey:@"favorite"];

    for (id obj in favorite)
    {
        NSLog(@"%@", obj);
    }
}

iOS Design Pattern Implementation

I'm struggling with design patterns and would like to follow best practices while rewriting my current app from Objective-C to Swift.

I have a game where a player gets extra scores/or special prizes for, let's say, solving a certain amount of levels. There are several milestones to be reached (such as 10 levels completed/50 levels completed). I have different game modes, so I have several subclasses of a Gameplay class. After each player's turn -checkSolution is being invoked to check whether the player solved the level. In case of success I increment the player's games score and send him to a new level . And here I also call -checkForMilestone of ScoreManager class to check whether any of the milestones has been reached.

I'm not sure whether it is ok to call -checkForMilestone inside -checkSolution. Or it might be better to create a callback using blocks or use KVO to observe (from ScoreManager class) whether the player's score was changed and then react appropriately.

***RESOLVED: searchDisplayController not updating UITableVIew

I have a UITableView with a Searchbar & Search Display Controller. My code appears to be correct but when I type in the searchbar, I get no results. The UITableView remains the same.

My segue is correct as it is still passing data correctly as well to the next VC just fine.

A push in the right direction would be appreciated.

**Note: I realize that searchDisplayController is deprecated starting with iOS8 but I want to figure this out for the sake of knowing.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [searchResults count];

} else {
    return [bands count];

}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"BandCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

if (tableView == self.searchDisplayController.searchResultsTableView) {
    cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
    cell.textLabel.text = [bands objectAtIndex:indexPath.row];
}

return cell;
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate *resultPredicate = [NSPredicate
                                predicateWithFormat:@"SELF contains[cd] %@",
                                searchText];

searchResults = [bands filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString
                           scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                  objectAtIndex:[self.searchDisplayController.searchBar
                                                 selectedScopeButtonIndex]]];

return YES;
}

EDIT

connections

I noticed that searchBar wasnt connected. When I connected this, I noticed that the searchbar would dissapear whenever I would tap inside it. It looks like the searchbar is dissapearing behind the navigation bar. Thats another issue for later.

I am still unable to get the table to update correctly.

Source: Source

EDIT

On a side note, I figured out why my searchbar was dissapearing. I had my tab bar embedded in a navigation controller when I should have had my navigation bar embedded in the tab bar.

So: Tab bar --> Navigation controller

Adding the following code stopped my searchbar from moving up and overlapping the status bar

self.definesPresentationContext = YES;

EDIT

Not sure why but I noticed that my searchbar / search controller was not wired correctly. I removed it and added it back and everything wired up correctly. Specifically:

missing connection

searchDisplayController was not wired up to Band list.

İOS how to make LINE to share image view [on hold]

I would like to share your photos via the application . How basıca of a button and the image line applications.please help me

UIAlertView in superclass and subclass

I have a superclass where I sometimes show an UIAlertView and handles the delegation (clickedButtonAtIndex). When I then have a subclass that also handles the "clickedButtonAtIndex" only the subclass delegation is called.

In both cases the UIAlertView is show like this:

[[[UIAlertView alloc] initWithTitle:@"" message:@"message" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:@"Open", nil]show];

Am I doing something wrong or is it bad design to have the same delegation in both the superclass and subclass. I thought the "delegate:self" separated them.

Tableview word wrap works in Simulator, but not on device

The following code wraps to multiple lines, as expected, on the 8.3 Simulator; but truncates the line when running on 8.3 iPhone 6. ????

Here is the code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    static NSString *simpleTableIdentifier = @"Active Playlist";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

     cell.textLabel.numberOfLines = 0;
     cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

    cell.textLabel.text = [playList objectAtIndex:indexPath.row];
    return cell;
}

WatchKit get data from closed App in iPhone

There are some application (example Runtastic) where is possible from the Watch to activate some function of the companion App even if the App is not running in the iPhone (never opened or closed). How is possible to make the same with my Apps? Thanks

Using MPMediaItem with simpleaudioengine

I've been making a project in cocos-2dx, but needed to create a .mm to select music from the iOS library to play in the background. I got it working by playing the music in the .mm file, but for various reasons, it needs to play in cocos-2dx using SimpleAudioEngine. I've tried converting the url's absoluteString to an NSString to an id to a const char* to move it back to the cocos-2dx files, but it still didn't run.

This is what it gave me for the absoluteString(ipod-library://item/item.m4a?id=456458322781804615)

.cc-

-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)collection{
if(collection){
    MPMusicPlayerController* appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];
    [appMusicPlayer setQueueWithItemCollection:collection];
    [appMusicPlayer play];
    MPMusicPlayerController *iPodMusicPlayerController = [MPMusicPlayerController iPodMusicPlayer];
    MPMediaItem *nowPlayingItem = [iPodMusicPlayerController nowPlayingItem];

    NSURL *url = [nowPlayingItem valueForProperty:MPMediaItemPropertyAssetURL];
    NSString *filePath= [url absoluteString];
    NSString *filePath2 = [url path];
    _songUrl = filePath;
 }
 -(id)returnsongUrl{
     return _songUrl;
 }

Second .mm

 const char* MediaPicker::songUrl(){
     id na1 = [[MediaPickerWrapper sharedIntance] returnsongUrl];
    const char *cString =  [na1 cStringUsingEncoding:NSASCIIStringEncoding];
    return  cString;
 }

Cocos-2dx file

  CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(media->songUrl());
  CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(media->songUrl(),false);

How to convert UPC-A to UPC-E?

We would like to convert the 12 digit UPC-A to 8 digit UPC-E. Can you tell me which is the best way to do this without having to use my own code to convert?

I got many formula for convert the 8 digit UCC-E to 12 digit UPC-A but not reverse.

IOS: keyword search in a list of passages only returns the last match, instead of all matches

i have one passage list and from that i want to find out keyword search from user, passage ID getting over ride in array and because of that only last passage showing the result.

i want search keyword from all passage and show the result .

- (UIViewController*) showContentWithQuery:(NSDictionary*)query
{
ContentViewController * viewController = nil;
if (query)
{

    NSNumber * sectionId = query[@"sectionId"];
    NSNumber * passageId = query[@"passageId"];

    if (sectionId)
    {
        viewController = [[[ContentViewController alloc] initWithSectionId:sectionId] autorelease];

        if (passageId)
        {

            viewController.tempHighlightPassageArray = @[passageId];
        }
    }
}

return viewController;     }

Change the colour of tab bar icons and table background under the "More" tab?

I have around 7 tab bar items and hence have been given a 'more' tab bar item. All the other tab bar items are using the 'Original' mode instead of 'Template' but when i select the 'more' tab, the remaining icons are back to 'Template' until they're dragged to the tab bar after pressing edit. As well as this, my other views are tableviews with a coloured background, when i select the 'more' tab, the tableview presented has a white background. I managed to fix this for the tableview but the cells within are white, with the empty cells having the correct colour. Any idea how i'd fix these issues?

iOS and unicode characters: \u+2605 not solid star in UILabel

I'm trying to make a UILabel that says "★ FEATURED". However, when it renders it, the star isn't solid! Here's the code I'm using:

    _sponsoredLabel = [UILabel new];
    _sponsoredLabel.numberOfLines = 1;
    _sponsoredLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _sponsoredLabel.textColor = [UIColor yellowColor];
    _sponsoredLabel.backgroundColor = [UIColor clearColor];
    _sponsoredLabel.textAlignment = NSTextAlignmentLeft;
    _sponsoredLabel.text = @"✭ FEATURED";
    _sponsoredLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0f];
    _sponsoredLabel.hidden = YES;

In the text itself it looks solid, but here's what it looks like when it renders:

Any advice is much appreciated!

cocos2dx - Alignment with LabelBMFont

I am trying and struggling to align the BMFontLabel with a sprite side by side. I am using code below to show score of the game with a coin on the left, and score on the right side..

Sprite *coin=Sprite::create("coinimg.png");
Label *scoreLbl=Label::createWithBMFont(GameConfig::scoreBigFont, strScore);
scoreLbl->setScale(.5);

MenuItemSprite *itemCoin=MenuItemSprite::create(coin);
MenuItemLabel *itemScore=MenuItemLabel::create(scoreLbl);

Menu *mainMenu=Menu::create(itemCoin,itemScore, NULL);

mainMenu->alignItemsHorizontallyWithPadding(0.0);

mainMenu->setPosition(Vec2(winsize.width*.1,winsize.height*.8));

The problem is I am getting is different alignments with different values I input like in image.

Thanks for help.

Transparent navigation bar in Ionic

My Ionic application have a detail view with transparent header. Applying CSS class "bar-clear" to my element is doing the job just fine in desktop browsers and when running the app on Android (see result here).

But when running on iOS 8 the header is white and opaque (see here).
Any idea why?

Delay in Corelocation

I've created a helper class for my location needs so i don't violate the DRY principle. The class looks like this:
Location.h

@interface Location : NSObject <CLLocationManagerDelegate>{
CLLocationManager *manager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}

-(float)latitude;
-(float)longitude;
-(NSString *)postalcode;

Location.m

@implementation Location{
    float latitude;
    float longitude;
    NSString *postalcode;
}
-(id)init{
    NSLog(@"Hallo");
    [self setupLocationManager];
    return self;
}

-(float)latitude{

    return latitude;
}

-(float)longitude{

    return longitude;
}

-(NSString *)postalcode{

    return postalcode;
}

-(void)setupLocationManager{
    manager = [[CLLocationManager alloc] init];
    [manager requestWhenInUseAuthorization];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.distanceFilter = 100;
    [manager startUpdatingLocation];
    geocoder = [[CLGeocoder alloc] init];
 }

 #pragma mark - CLLocationManagerDelegate Methods

 - (void)locationManager:(CLLocationManager *)manager didFailWithError:          (NSError *)error
{

     NSLog(@"Error: %@", error);
     NSLog(@"Failed to get location! :(");

}

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

NSLog(@"Location: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {

    latitude = currentLocation.coordinate.latitude;
    longitude = currentLocation.coordinate.longitude;


}

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

    if (error == nil && [placemarks count] > 0) {

        placemark = [placemarks lastObject];
        postalcode = [NSString stringWithFormat:@"%@",placemark.postalCode];
        /*
         self.address.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
         placemark.subThoroughfare, placemark.thoroughfare,
         placemark.postalCode, placemark.locality,
         placemark.administrativeArea,
         placemark.country];
         */
    } else {

        NSLog(@"%@", error.debugDescription);

    }

} ];

}


 @end

When i in my ViewController tries to create an instance of Location and set latitude and longitude labels, in the viewDidLoad method, the labels are sat to 0.00000. Apparently it takes around half a second for Location to get the coordinates. I've tried using

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self setCoordinateLabels];
    });

But that just seems very hacky and can't possibly be the best practise? So is there any way i could do this a better way?

Failing to install SwiftyJSON

I want to include SwiftyJSON into my Xcode 6.3 project.

When I try to build it get about 40 compiler errors. Most of them are similar to 'AnyObject' is not convertible to 'String'. Did you mean as! to enforce downcast?

I followed the tutorial steps:

  1. Download SwiftyJSON (http://ift.tt/Z2t6lA)
  2. Drag and drop the SwiftyJSON.swift to my Xcode project.
  3. Accepting the "copy if necessary".
  4. Re-build project.

My best guess is that since I'm so new I'm missing some very "obvious" step.

Tutorial used: http://ift.tt/1tkN0Ql

Get the end of a string in a uitextview

I want to create a message box just like Telegram and others chats, that have a time in the down side of the box.

But if the text ends in the end of the line, the time label should be in the next line, otherwise, should stay in the same line.

So, I want something like this: new line for date when content is goes until the end

How to accomplish this in my xib, or programatically ?

Thanks in regards,

Make an object appear in frame N and not frame 0 in SpriteBuilder

In SpriteBuilder, every object starts at frame 0.

I have some objects that will fall from the sky, but I want their falling animation (physics with gravity) to begin later in the scene, and not at 0.

Can I either have the objects exist at a certain frame? (i.e. insert empty frames before the object's first keyframe), or can I have the objects queue the physics gravity after a certain frame?

tia

AVAssetExportSession export fails non-deterministically with error: "Operation Stopped, NSLocalizedFailureReason=The video could not be composed."

We add subtitles to a video recorded by the user, but the export by our AVAssetExportSession object fails non-deterministically: sometimes it works, and sometimes it doesn't. It's unclear even how to reproduce the error.

Error:

Error Domain=AVFoundationErrorDomain Code=-11841 "Operation Stopped" UserInfo=0x170676e80 {NSLocalizedDescription=Operation Stopped, NSLocalizedFailureReason=The video could not be composed.}

Code:

    let videoAsset = AVURLAsset(URL: fileUrl, options: nil)
    let mixComposition = AVMutableComposition()
    let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
    let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))

    let sourceVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0] as! AVAssetTrack
    let sourceAudioTrack = videoAsset.tracksWithMediaType(AVMediaTypeAudio)[0] as! AVAssetTrack
    videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: sourceVideoTrack, atTime: kCMTimeZero, error: nil)
    audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: sourceAudioTrack, atTime: kCMTimeZero, error: nil)

    // Create something mutable???
    // -- Create instruction
    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
    let videoLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: sourceVideoTrack)
    instruction.layerInstructions = [videoLayerInstruction]

    let mutableComposition = AVMutableVideoComposition()
    //mutableComposition.renderSize = videoTrack.naturalSize
    mutableComposition.renderSize = CGSize(width: 320, height: 320)
    mutableComposition.frameDuration = CMTimeMake(1, 60)
    mutableComposition.instructions = [instruction]

    // Animate
    mutableComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)

    // -- Get path
    let fileName = "/editedVideo-\(arc4random() % 10000).mp4"
    let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let docsPath = allPaths[0] as! NSString
    let exportPath = docsPath.stringByAppendingFormat(fileName)
    let exportUrl = NSURL.fileURLWithPath(exportPath as String)!

    println("Num of tracks \(mixComposition.tracks.count)")

    // -- Remove old video?
    if NSFileManager.defaultManager().fileExistsAtPath(exportPath as String) {
        println("Deleting existing file\n")
        NSFileManager.defaultManager().removeItemAtPath(exportPath as String, error: nil)
    }

    // -- Create exporter
    let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
    exporter.videoComposition = mutableComposition
    exporter.outputFileType = AVFileTypeMPEG4
    exporter.outputURL = exportUrl
    exporter.shouldOptimizeForNetworkUse = true

    // -- Export video
    exporter.exportAsynchronouslyWithCompletionHandler({
        self.exportDidFinish(exporter)
    })

Questions:

1) What's causing the problem, and what's the solution?

2) Suggestions on how to reproduce the error consistently, which hopefully helps debug the problem?

Libgdx/RoboVM write UIImage/bytes to file

I need to write an image from the IOS gallery to a file to be used in my app. I dont speak Obj-C, neither can I translate Obj-C to RoboVM´s Java library. What I think would be the easiest for me to understand is to use InputStream to write the image to a file. So this is what I got going so far:

@Override
public void iosPickImage(final InputStream stream) {
    // Gallery
    MyDelegatePicker delegate = new MyDelegatePicker() {
        @Override
        public void didFinishPickingMedia(UIImagePickerController picker, UIImagePickerControllerEditingInfo info) {
            UIImage selectedImage = info.getOriginalImage();
            File file = new File(Gdx.files.getExternalStoragePath() + "selectedPhoto1.bin");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                FileInputStream fileStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


            try {
                stream.read(selectedImage.toPNGData().getBytes());

            } catch (IOException e) {
                e.printStackTrace();
            }
            picker.dismissViewController(true, null);
        }

        @Override
        public void didCancel(UIImagePickerController picker) {

        }
    };
   UIViewController controller = ((IOSApplication) Gdx.app).getUIViewController();
    MyImagePickerController imagePicker = new MyImagePickerController();
    controller.addChildViewController(imagePicker);
    controller.getView().addSubview(imagePicker.getView());
    imagePicker.getView().setBounds(controller.getView().getBounds());
    imagePicker.setSourceType(UIImagePickerControllerSourceType.PhotoLibrary);
    imagePicker.setDelegate(delegate);
    imagePicker.addStrongRef((ObjCObject) delegate);


    //Gdx.app.exit();

}

And then by passing that method through my interface :

public void iosGallery(final InputStream stream) {
    gallery.iosPickImage(stream);


}

This as you can see is far from finished. I would like to use Callback and AsyncExecutor to finish this off, but the RoboVM library dont support those classes. So anyone got an idea on how to finish this method or rewrite it to work?

Unexpectedly found nil while unwrapping an Optional value (UIButton)

I'm trying to create a button programmatically and add it to a UIScrollView in Swift. The code below is what I am using and throws the infamous "unwrapping optional error" where I add the button as a subview. Why is it doing this? I have checked and compared my code to others' and all seems to look fine.

let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(8, 2, 200, 300)
button.backgroundColor = UIColor.grayColor()
button.setTitle(productName, forState: UIControlState.Normal)
self.productButtonView.addSubview(button) //This line throws error

Thank you in advance.

UIActionSheet crashes on iPad swift

I have the following button action in a toolbar:

  @IBAction func share(sender: AnyObject) {
        let modifiedURL1 = "http://ift.tt/1GDOWdL"
        let modifiedURL = modifiedURL1.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil)

        let alert = UIAlertController(title: "Share", message: "Share your findings", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let twBtn = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default) { (alert) -> Void in
            if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){
                var twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
                twitterSheet.setInitialText("Look what I found on Declassified and Ratified: \(modifiedURL)")
                self.presentViewController(twitterSheet, animated: true, completion: nil)
            } else {
                var alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }

        let fbBtn = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default) { (alert) -> Void in
            if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){
                var facebookSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
                facebookSheet.setInitialText("Look what I found on Declassified and Ratified: \(modifiedURL)")
                self.presentViewController(facebookSheet, animated: true, completion: nil)
            } else {
                var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
        let safariBtn = UIAlertAction(title: "Open in Safari", style: UIAlertActionStyle.Default) { (alert) -> Void in
            let URL = NSURL(string: modifiedURL)
            UIApplication.sharedApplication().openURL(URL!)
        }
        let cancelButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (alert) -> Void in
            println("Cancel Pressed")
        }

        let textBtn = UIAlertAction(title: "Message", style: UIAlertActionStyle.Default) { (alert) -> Void in
            if (MFMessageComposeViewController.canSendText()) {
                let controller = MFMessageComposeViewController()
                controller.body = "Look what I found on Declassified and Ratified: \(modifiedURL)"
                controller.messageComposeDelegate = self
                self.presentViewController(controller, animated: true, completion: nil)
            }
        }


        alert.addAction(twBtn)
        alert.addAction(fbBtn)
        alert.addAction(safariBtn)
        alert.addAction(textBtn)
        alert.addAction(cancelButton)
        self.presentViewController(alert, animated: true, completion: nil)
    }

However, this code crashes when called on an iPad with a sigbart crash (that is all I can see in the console). I see this is a common problem but the other solutions have not worked for me. I even set the version to the latest iOS and that didn't fix it. Can someone explain?

Swift - Starting a game with out pressing the screen

I am making a game that, when the game loads in, doesn't require the user to tap the screen to start, but starts straight away.

My code with the "tap to start":

import Foundation
import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var isStarted = false

    override func didMoveToView(view: SKView) {
        //backgroundColor = UIColor.greenColor()

        addTapToStartLabel()

    func addTapToStartLabel() {
        let tapToStartLabel = SKLabelNode(text: "Tap to start!")
        tapToStartLabel.name = "tapToStartLabel"
        tapToStartLabel.position.x = view!.center.x
        tapToStartLabel.position.y = view!.center.y + 40
        tapToStartLabel.fontColor = UIColor.whiteColor()
        tapToStartLabel.fontName = "Helvetica"
        tapToStartLabel.fontSize = 22.0
        addChild(tapToStartLabel)
    }

    func start() {
        isStarted = true

        let tapToStartLabel = childNodeWithName("tapToStartLabel")
        tapToStartLabel?.removeFromParent()

        square1.stop()
        movingGround.start()
        wallGen.startGenWallsEvery(1)
        diamondGen.startGenDiamondsEvery(1)
    }

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

        if isGameOver {
            restart()
        } else if !isStarted {
            start()
        } else {
            square1.flip()
        }
    }

I have tried a couple of things and I can't seem to figure it out.

How can I recieve messages in my app IOS

I am creating an app and I want to receive messages in my own app. How can I do it? I have searched around a bit and I was unable to find any resource on the web. I hope I can get solution from this community.

UISegmentedControl unselect segment by pressing it again

How can one unselect a given segment in a UISegmented control, by pressing the same segment again?

E.g. Press segment 0, it becomes selected and remains highlighted. Press segment 0 again and it becomes unselected and unhighlighted.

The control only fires UIControlEventValueChanged events. Other events don't seem to work with it.

There is a property 'momentary' which when set to YES almost allows the above behavior, excepting that highlighting is only momentary. When momentary=YES pressing the same segment twice results in two UIControlEventValueChanged events, but when momentary=NO only the first press of a given segment results in a UIControlEventValueChanged event being fired. I.e. subsequent presses on the same segment will not fire the UIControlEventValueChanged event.

ReactiveCocoa takeUntil 2 possible signals ?

So I am trying to get the timer to stop upon a completed signal from my updated table and it appears not to be working.

I have gotten the signal to stop when the button is pressed the second time that works well.

However I tried to created a second signal to allow the scheduler to stop, and it does not appear to stop in both options 1 and 2 in the update table view.

Am I writing this correctly, is there a concept I am not understanding?

-(RACSignal*) startTimer {
    return [[[[RACSignal interval:1.0
            onScheduler:[RACScheduler mainThreadScheduler]]
             startWith:[NSDate date]]
             takeUntil:[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]]
             takeUntil:self.completeSignal];
}

-(void) viewDidLoad {


    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    RACSignal* pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];

    @weakify(self);
    RACSignal* textChangeSignal = [[pressedStart map:^id(id value) {
        @strongify(self);
        return [self.start.titleLabel.text isEqualToString:@"Start"] ? @"Stop" : @"Start";
    }] startWith:@"Start"];

    [textChangeSignal subscribeNext:^(NSString* text) {
        @strongify(self);
        [self.start setTitle:text forState:UIControlStateNormal];
    }];


    static NSInteger t = 0;
    [[pressedStart flattenMap:^RACStream *(id value) {
        return [self startTimer];
    }] subscribeNext:^(id x) {
            t = t + 1;
            NSLog(@"%ld",t);
        [self updateTable];
    }];





}

-(void) updateTable {

    // option 1 Doesn't work
        [self.start    sendActionsForControlEvents:UIControlEventTouchUpInside];
// Option 2 doesn't work 
self.completeSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendCompleted];
        return nil;
    }];
    if ([self.excercises count] > 0 || self.excercises !=nil) {

    }else {
        // stop everything
        // using button signal
    }




}

OpenEars in Swift?

I just created an empty swift project and imported the OpenEars framework.

I followed the method mentioned here for bridging: How to call Objective C code from Swift

In the bridge file it says all header (.h) files are missing. Where did I go wrong?

Here's my project: http://ift.tt/1CAlogg

UI_APPEARANCE_SELECTOR required or not?

For below code to work we should generally define a aFont property in TestView.h with UI_APPEARANCE_SELECTOR. But, it seems it is not required. I tried with and without the UI_APPEARANCE_SELECTOR, results are the same.

I don't know if this is right or wrong?

[[TestView appearance] setAFont:[UIFont boldSystemFontOfSize:20.0f]];

#import "ViewController.h"
#import "TestView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
     [[TestView appearance] setAFont:[UIFont boldSystemFontOfSize:20.0f]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

TestView.h

#import <UIKit/UIKit.h>

@interface TestView : UIView
@property (strong,nonatomic) UIFont *aFont  ;
@end

TestView.m

#import "TestView.h"

@implementation TestView
{
    UILabel *aTestLabel;
}
@synthesize aFont=_aFont;

- (void)drawRect:(CGRect)rect {
    // Drawing code
    NSLog(@"A Font= %@ ",_aFont);
}


-(id) init{
    self=[super init];
    if(self){
        [self addLabel];
    }
    return self;
}

-(id) initWithCoder:(NSCoder *)aDecoder{
    self=[super initWithCoder:aDecoder];
    if(self){
        [self addLabel];
    }
    return self;
}

-(void)addLabel{
    aTestLabel=[[UILabel alloc] initWithFrame:self.bounds];
    aTestLabel.text=@"Hello";
    _aFont=[UIFont systemFontOfSize:10.0];

    [self addSubview:aTestLabel];
}

-(void)setAFont:(UIFont *)aFont{
    _aFont=aFont;
    aTestLabel.font=_aFont;    
}

How to process words one by one?

how can I pick words from a paragraph and process one by one. I want to switch places of letters except first and last letter. How can I? Thanks

Sharing of Image and text with Deep linking on facebook in ios8

Have anyone worked on deep linking in ios 8? I tried to follow facebook.developer tutorial to implement deep linking but is not so much clear. please suggest me any blog and tutorial or sample code. Any help will be appriceate. Thanks in advance!

How to cast to generic type in Swift

I am about to learn Swift. I want to write a class, that handles Cora Data tasks for me. In this case, it should be possible to pass an entity name and and array of tuples to a function, which then interprets the tuples as key value pairs for NSPredicates to retrieve ManagedObjects matching them. Because of NSPredicate needing values with specific types, I tried to pass the types of the values, too. But I can't get around that "'t' is not a type" compile error (last line of code). How can I cast the value to an passed type? Or would you create the NSPredicate in a totally different way?

class func getManagedObjectsWithEntityName<T>(entityName: String, keysAndValues: [(key: String, value: AnyObject, type: T.Type)]) -> [NSManagedObject] {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: entityName)
    var predicates: [NSPredicate] = []

    for tuple in keysAndValues {
        let t = tuple.type
        predicates.append( NSPredicate(format: tuple.key + " = %@", tuple.value as t)!)
    }

    ...
}

PickerView bug with selectedRowInComponent()

I'm having a weird bug with PickerView - I have three components in a PickerView, where the first component selects the main category, the second component selects the sub category, etc.

So, in my pickerView(..., numberOfRowsInComponent) function, I detect which row is selected in the first component using selectedRowInComponent(0), and then feed in the correct count of rows for the second component.

Some strange bug is occuring though... I've coded it so that if the first row (row 0) is selected on component 0, then the second and third components both have only 1 row each. But if component 0's second row is selected (row 1), there should be 5 rows in the second and third component.

In the viewOnLoad function of this corresponding view, I have it so I automatically select the second row of the pickerView's first component (using picker.selectRow()). This should mean that my second component will automatically appear with five rows. But instead, when I run my app, the second row is selected in component 0, but the second and third components only have 1 row each. It seems like it's bugging out and thinking that the first row is selected. Weird thing is that if I change the first component's row to something else and then back to row 1, it suddenly has the correct number of rows in components 1 and 2.

Hopefully this makes sense, hard to describe. Happy to post pictures if need be. Anyone know what I might be doing wrong?? Thanks!

Cannot find libcocos2d ios.a library in Xcode

I have downloaded the cocos2d-x 3.6 yesterday. And I do follow the steps in this tutorial page: http://ift.tt/1v5QE5a.

I build and run my new project in Xcode successfully. But I notice that there is no "libcocos2d ios.a" library existed when I click my project setting. I try to search the answer from internet, but it seems doesn't have correct one.

One more thing, if I clean the whole project and rebuild it. It will compiling 621 source files to come out(I think it's cocos2d source files), it takes too long time! I don't want to wait so long every time when I clean and rebuild project. Is there a way to make it don't rebuild cocos2d-x source files every time?

the screenshot: enter image description here

--------------- environment ---------------
Xcode 6.3.2
Mac OS 10.10.3
cocos2d-x 3.6


I find a possible solution here: http://ift.tt/1HnZmVF

After trying, the Xcode project failed to link those two generated "libcocos2d ios.a" files(one for arm7, the other for arm64). I still don't know why this happened. I am building project for iPhone 6(arm64), why it says require i386 architecture.

here is the error (build for iPhone 6 simulator): enter image description here

Storing images from [UIImage] array to Parse

I have an UIImage array, images, which is declared as

var images = [UIImage]()

I currently have pictures stored in there, and when I output it using the println() function, I get

[<UIImage: 0x195dc810>, <UIImage: 0x195da3e0>, <UIImage: 0x1950ab50>]

I was wondering how I could upload these images to Parse as one row.

Here is my full code of what I have now(not working):

@IBAction func saveToParse(sender: AnyObject) {

    for var i = 0; i < images.count; i++
    {
        var objectForSave:PFObject = PFObject(className: "NewLog")
        //error on this line below:  [(UIImage)] does not have a member variable named 'objectAtIndex'
        let imageData:NSData = NSData(data: UIImagePNGRepresentation(images.objectAtIndex(i) as! UIImage))

        var imageFile:PFFile = PFFile(data: imageData)
        imageFile.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
            if success{
                objectForSave.setObject(imageFile, forKey: "Image")

                objectForSave.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
                    if success{
                        //do smth
                    }else{
                        println(error)
                    }
                })

            }else{
                println(error)
            }

            }, progressBlock: { (progress:Int32) -> Void in

        })


    }     
    } 

Thank you.

Assigning a delegate to a background job for dropbox upload

I am using Dropbox's SDK API V1 to upload files from my iOS app. The files aren't loading in real time, but rather I push them into a queue, and they get uploaded in the background.

I can't figure out for the life of me how to take DB RestClient delegate and make it respond to a completion/failure event that happens in the background. Is that even possible?

It seems (and I am new here), that delegates are meant to respond to live events on screen. Is that even an option to assign them to anything other than a UI element/view?

UITableView cell gives different widths. How to solve this?

I have the function heightForRowAtIndexPath to calculate the height of the cell having two textfields of dynamic text

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    let cell = tableView.dequeueReusableCellWithIdentifier(self.kkCellIdentifier) as! NibTableViewCell
    cell.updateConstraints()
    let width = cell.contentView.frame.width
    //use width to calculate the height
}

I am running this on iPhone 6 simulator.

In portrait:

I get cell width sometimes as 375 (wrong- it is actually tableView's frame width) and sometimes as 320 (Correct one)

In Landscape:

I get cell width sometimes as 320 and sometimes as 659 (Correct one)

Why is it like this? Is this a bug?

How to solve this?

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

How to change duration of ImageView in Objective-C

I am creating a simple camera app for a photobooth. This code below is a sample of the whole project, I am using AVFoundation because I needed my own custom requirements.

When the user presses a button, it takes a photo and instantly shows the preview in the imageView. This is my first major coding project and am new to Objective-C. Is there a way to add a timer or duration to the imageView so that it then removes the image from it, or a way to cycle to a second black image after some time, ready for the next user to take their photo?

Many thanks for any help suggested!

- (IBAction)takephoto:(id)sender {

    AVCaptureConnection *videoConnection = nil;

    for (AVCaptureConnection *connection in StillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts ]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
    }
    [StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer != NULL) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            imageView.image = image;
        }
    }];
}

Swift code completion not working with Cocoapods

I have an demo app that uses various internal development pods written in swift. All of the swift code in the development pods has trouble code completing. For example, when holding command and clicking on import UIKit, Xcode complains of a Symbol Not Found when tapping on UIKit. There's no compiler errors, everything builds and runs just fine.

If I have swift code outside of the pod in the demo project itself, that code completes just fine, but when I put it in a pod and run pod install, it either stops code completing immediately, or works for a few hours / pod update commands, and then randomly stops working. I have other development pods in my project, and those written in Objective-C have no trouble code completing ever.

I have tried multiple different solutions, namely the solutions listed here: Xcode 6 Swift code completion not working. None of these worked for me.

I tried various combinations of these solutions from the post above multiple times:

  • deleting Xcode's derived data
  • selecting a different simulator device to force a re-index
  • deleting Cocoapod's cache (both in the library and the Podfile.lock and Pods directory)
  • running pod deintegrate and then pod install
  • restarting Xcode and computer
  • using different versions of Xcode (6.3.2, 6.4, 7.0-beta2)
  • on a completely different machine

None of which seem to work.

Any help would be greatly appreciated!

How to add collection view programmatically in iOS

i want to add UICollectionview when i click on a button.. The default screen has table view already. I am adding grid option button and want to arrange data in grid by collection view when user click on grid button

How can I program hundred eighty barcode scanner?

I am in a need to develop an app for iOS. I want to connect that app with the hundred eighty barcode scanner. My client wants to use only this scanner as he feels it is cheaper than other scanners. I don't know how to program it. Does socketmobile SDKs help to program this scanner? Or is there any other way to program the hundred eighty scanner? Please, someone help me out.

Sprite-Kit Swift: How can I drag a SpriteNode across the screen

I have a SpriteNode which is a ball. It drops down the screen and I want to drag and release so that it can move by itself towards the top of the screen where a laser will destroy it. The ball itself is affected by gravity. What code do I need to write in touches began so that I can specify that when I touch the ball the above description starts.