mardi 4 août 2015

sqlite3_close_v2 crashes on iOS, sqlite3_close doesn't

I'm writing some sqlite3 code in iOS for the first time. Every time I try and close the sqlite3 database connection with sqlite3_close_v2(db) where db is a sqlite3 * obtained from a call to sqlite2_open_v2, the application crashes with no helpful console output or other information but only on an actual device - it doesn't crash in the simulator.

Here's a code sample:

sqlite3_stmt *statement = NULL;
int returnCode = 0;
if((returnCode = sqlite3_prepare_v2(db, [query UTF8String], (int)strlen([query UTF8String])+1, &statement, NULL)) != SQLITE_OK || statement == NULL) {
    Log(@"Failed to create query. code:%d",returnCode);
    sqlite3_close_v2(db);
}

The code will crash on the last line in the if statement when I pass a bad query. The code will not crash on the simulator, but it will crash on both an iOS 8 iPad and an iOS 7 iPod.

The crash is reported like this (this is not my own breakpoint, by the way):

dyld`dyld_fatal_error:
->  0x1200e5088 <+0>: brk    #0x3

The breakpoint indicator says the crash is Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1200e5088).

Thread crash log

Can anyone help me debug this? I've spent a lot of time googling around to no avail. For now, I'm going to just use sqlite3_close(db), as this does not crash, but I'm worried about any consequences of using the v2 open method with the non-v2 close method...

How does Quettra Portrait get the list of installed apps on non-jailbroken iOS devices?

According to the Quettra Portrait for iOS Privacy Policy they manage to get a list of installed apps on iOS. What's more, they're able to do this from an App Store approved app on non-jailbroken devices. Every Google/StackOverflow search I've done on the matter suggests that this is impossible, but Quettra is somehow able to do it without raising the ire of Apple. Any ideas?

swift iOS resize view on scroll

I have a VC with a navigation bar and then a uiview under it that acts as an extension to the navbar.

Then I have a embedded table view.

What I would like to do is to add a scroll recogniser to the container view that holds the table view so when I scroll down the uiview under the navigation bar should be hidden.

Is this possible? I have used self.navigationController?.setNavigationBarHidden(true, animated: true) In order to hide the navigation bar and that works. The problem is that I now need to hide the uiview under it. And I can't get it to work/feel smooth since just a hide/show functions looks strange. I would like it to be hidden the same speed as I scroll

Can I avoid reaction delay (nearly 1s) in web pages on iPhone 6?

Question

Is there any way, perhaps hardware acceleration, or WebGL, or anything, anything, I can do to speed up touch reaction speed on iPhone? I would really like the reaction to appear instant.

My problem

I noticed that my menu was taking nearly a full second to react to its icon being tapped on an iPhone 6, while the menu reacts instantly to a click on desktop. I notice this seems to be the case with all the mobile websites I visited for testing, and the ~1s delay is really bothersome, it takes away that crisp, reactive feel from the web application. Installed applications on iOS, on the other hand react instantly to touch, so I know it isn't the touch detection speed.

Example

I created an example to test this out:

var size = 'norm';
var $box = $('#box').on('click', function () {
    if (size == 'norm') {
        $box.css({
            'width' : '1in',
            'height' : '1in'
        });
        size = 'big';
    } else {
        $box.css({
            'width' : '',
            'height' : ''
        });
        size = 'norm';
    }
});
#box {
    width:0.5in;
    height:0.5in;
    margin:0.5in;
    background-color:violet;
}
<script src="http://ift.tt/1oMJErh"></script>
<div id="box"></div>

Tap the box on an iPhone and you'll see what I mean.

What I've tried

I tried inserting -webkit-transform: translateZ(0); into the item's style to activate hardware acceleration, but this didn't seem to improve speed.

Spotify Embed Doesn't work on iPhone or iPad

I am using a Spotify embed on a new website that is being built in WordPress. The embed works just fine on a computer. However, on my iPad and iPhone it doesn't work. The player shows up just fine, but when I click on a track, it pops up a window that gives me the option to "Download Spotify" or "I Have Spotify." I have Spotify on both devices, but when I tap on the "I Have Spotify" button the window closes but nothing happens. Here's an example of the code I am using to play three songs in a player:

<iframe src="http://ift.tt/1IiG2qb" width="293" height="373" frameborder="0"></iframe>

Am I doing something wrong or does it just not work on iOS devices?

Thanks for any advice and/or help.

how to make my win label stay hidden until the user win?

am trying to make my label hidden by changing the x and y parameter but when i start playing the game and on the first click suddenly the label appear i tried the alpha way and all the other way to hide a label were fine except this one.

this my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!


    var goNumber = 1

    var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0]

    let winnerCombination = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

    var winner = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


  override func viewDidAppear(animated: Bool) {
        self.label.center = CGPointMake(self.label.center.x - 400, self.label.center.y)

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
        @IBAction func buttonPressed(sender: UIButton) {

        if gameState[sender.tag] == 0 {
            var image = UIImage(named: "")
            if goNumber % 2 == 0 {
                image = UIImage(named: "cross.png")
                gameState[sender.tag] = 1
            }
            else{
                image = UIImage(named: "nought.png")
                gameState[sender.tag] = 2
            }
            for combination in winnerCombination {

                if (gameState[combination[0]] == gameState[combination[1]] && gameState[combination[0]] == gameState[combination[2]] && gameState[combination[0]] != 0) {

                    winner = gameState[combination[0]]

                    println("the winner is \(winner)")
                }
            }
            if winner != 0 {

                if winner == 1 {
                    label.text = "cross won"
                }
                else {
                    label.text = "nought won"
                }
                UIView.animateWithDuration(0.5, animations: {
                    self.label.center = CGPointMake(self.label.center.x + 400, self.label.center.y)

                    self.label.alpha = 1
                })
            }
            sender.setImage(image, forState: .Normal)
            goNumber++
        }
    }
}

Scroll View Size not match with the device screen in xcode

Ok, I tried the page with several buttons but all of them will not fit in one screen. So, I create the scroll view and the view and then put all of buttons inside the view. The storyboard look fine. Other devices such as iPhone 5 and 5S look fine but when I tried 6 and 6 plus, the size of scroll view was incorrect. I couldn't figure what went wrong.

storyboard

tree1

tree2

iPhone 5s

iPhone 6

Swift Airdrop Save Device Name To App

When you see someone's device name through Airdrop (when using iPhones/iPads, for example), is there any way to programmatically get and store that device name? I thought it might involve the UIDevice class, but that seems more for getting my OWN device name.

In my app, I'd like to set up a local dictionary for frequently-encountered contacts, where the user can take a picture and save it along with the peer's device name (right now you can't always guarantee the other person will have a photo associated with his or her device). I know how to take and store a picture programmatically. I just need to figure out how to access and save another person's device name when in Airdrop range to associate with the photo.

I'm open to other methods besides Airdrop to get and store a device name to associate with a photo, but I want to keep the ability to read only devices that are within close proximity of the sender's device. Airdrop just seems like a good way to do that.

Thanks in advance.

Dynamic cell height in UITableView with variable number of subviews

I was wondering if someone could help me in this feature for dynamic cells for UITablewView.

I need to add subviews to a cell depends on some context. So the cell will grows if a have more than one of this subviews:

enter image description here

I'd like to know how can I add this subviews programatically and how to make the cells grows dynamic using constraints?

How to save video recording to documents directory with swift?

I have written this code to record video and would like to save the filePath to the documents directory, how can I do this?

func startRecording() {
    var currentDateTime = NSDate()
    var formatter = NSDateFormatter()
    formatter.dateFormat = "MM-dd-yyyy, hh:mm:ss a"
    var recordingName = formatter.stringFromDate(currentDateTime) + ".mp4"
    var pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
        videoRecorder = UIImagePickerController()
        videoRecorder.delegate = self
        videoRecorder.sourceType = UIImagePickerControllerSourceType.Camera
        videoRecorder.mediaTypes = [kUTTypeMovie]
        videoRecorder.videoMaximumDuration = 3600.0
        videoRecorder.startVideoCapture()
    }
}

UIStoryboardSegue: top view is not sliding down

I have the following swift code and what i am trying to achieve is a segue that slides off the top. I want the secondVCView to be below the firstVCView and for the firstVCView to slide off displaying the secondVCView.

Currently there is no animation and it just flashes to the secondVCView.

Many Thanks

import UIKit

class TopToBottomSegue: UIStoryboardSegue {

override func perform() {

    // Assign the source and destination views to local variables.
    var firstVCView = self.sourceViewController.view as UIView!
    var secondVCView = self.destinationViewController.view as UIView!

    // Get the screen width and height.
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(0, 0, screenWidth, screenHeight)

    // Access the app's key window and insert the destination view below the current (source) one.
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(secondVCView, belowSubview: firstVCView)

    // Animate the transition.
    UIView.animateWithDuration(0.4, animations: { () -> Void in

        firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, screenHeight)
        //secondVCView.frame = CGRectOffset(secondVCView.frame, -screenWidth, 0.0)

        }) { (Finished) -> Void in
            self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                animated: false,
                completion: nil)
    }

  }
}

CABasicAnimation - view should position on the last frame

Hello i want to do a CABasicAnimation rotation where my view rotates 440 degree. After the animatin i don´t want to reset the view to the old position. It should be on the same position like on the last frame of the animation.

CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];

rotate.toValue = [NSNumber numberWithFloat:degrees / 180.0 * M_PI];
rotate.duration = 4.4;
[rotate setFillMode:kCAFillModeForwards];
UIView *animationView = [self getBGContainerViewForSender:sender];
[animationView.layer addAnimation:rotate forKey:@"myRotationAnimation"];</i>

Can anybody tell me how to position the view on the last frame?

UITableView is displayed half of the screen after converting to Universal app

I want to convert an iphone app to universal. the iphone storyboard has a UITableView. I used Auto-layout and Use Size Classes using the latest XCode and added missing constraints however I cannot make the tableView and its cells go all the way down; it's only half way of the screen. Can anyone have an idea on how to do this; Thank you very much. I attached the screenshot here View Screenshot

I want to make Custom Lock Screen iOS app

I am making custom lock screen app for iOS, having a locker type objects with user defined color matching scheme to open locked screen, Can anybody help me while providing useful tutorial or any other useful material coding or anything else helpful in this regards that how to make a lock screen app programmatically?

bootstrap slider not showing tooltip on iphone 6, mobile device

Hi just found an issue on bootstrap sliders which you can download from http://ift.tt/1lwYnrc or http://ift.tt/1bHa8Vr

both of these plugins seem to be having the same issue on iphone 6 - the tooltip is not showing up when sliding the slider. I have checked only on iphone 6 but i assume the same issue is for other mobile devices. Has anyone found a solution for that?

Where is iCloud Drive for Sandbox?

I create a folder on iCloud Drive using this:

NSFileManager *fManager = [NSFileManager defaultManager];

NSURL *ubiq = [fManager URLForUbiquityContainerIdentifier:nil];
NSURL *iCloudDocumentsURLTemp = [ubiq URLByAppendingPathComponent:@"Documents"];

NSError *error = nil;

if (![fManager fileExistsAtPath:iCloudDocumentsURLTemp.path]) {
  [fManager createDirectoryAtURL:iCloudDocumentsURLTemp
     withIntermediateDirectories:YES
                      attributes:nil
                           error:&error];      
}

The first time I run this, it creates the folder. The second time it says the folder already exists.

I don't see the folder on icloud.com or in beta.cloud.com.

How do I see the folders/files I am creating there?

Why doesn't my best score value load after game closes and launches again? (Swift)

My best score value works perfectly fine if the game keeps running, but it won't load the best score if the game closed and was to launch again. It goes back to zero every time it the launches again.

Here is what I'm doing:

import SpriteKit

class EM: SKScene, SKPhysicsContactDelegate {

var bestScoreText = SKSpriteNode()

let bestScoreCategory: UInt32 = 1 << 4

var bestScoreLabelNode = SKLabelNode()
var bestScore = NSInteger()

override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    var bestScoreDefault = NSUserDefaults.standardUserDefaults()

    if (bestScoreDefault.valueForKey("bestScore") != nil) {
        bestScore = bestScoreDefault.valueForKey("bestScore") as! NSInteger!

    }
.......
....... 
     bestScore = 0
  }



func didBeginContact(contact: SKPhysicsContact) {


    if (score > bestScore) {

        bestScore = score

        var bestScoreDefault = NSUserDefaults.standardUserDefaults()
        bestScoreDefault.setValue(bestScore, forKey: "bestScore")
        bestScoreDefault.synchronize()

    } else {
......
}

Swift ios is it bad to have an embedded table view

I wonder if there is any downside in having an embedded table view?

I have a navigation controller VC that leads to another VC which is my apps "main/root" VC.

Inside that VC I have a container view which holds an table view.

Is this a bad setup? The table view then has more segues leading to other VC's

Videos recorded from app has incorrect creation date from PHAsset

I have an app that records video and displays them in a certain order. The videos recorded in my app has the correct date, but the times were all the same. So, all of the video recorded today show: 2015-07-31 13:15:51 +0000

I'm not setting any properties related to time in my capture session or movie output. I can't seem to find any documentation on how to do this properly. Does anyone have an idea?

Thanks!

Update: I recorded more video within the app. Turns out that the date is also wrong. It’s creation date reads the same as all the other videos created previously. For kicks, I delete the app from my phone, recorded a new video. It has the correct day and time. But after recording a second video, the date and time is the same as the previous recorded video.

xcode build is fine for some platforms, but failed with others (files not found)

My project builds perfectly for iPhone6(8.4), 6+, 5s, iPad air, but fails for iPhone 5, 4s, iPad retina and iPad2. It fails also if I build it for my own iPhone6(8.4), whereas it works for the same device in simulator. It therefore prevents me from making an archive.

Each time, it is the same errors : use of undeclared type... As shown below

build fails

It looks like it doesn't find the DrawerController framework.

I've tried to clean several times, to start again XCode, to remove and add the framework, to add them into embedded libraries, but nothing works.

I can not manage to find what I may have did wrong, as it works perfectly for some architectures, so the frameworks are found for those ones.

Thanks

direct video streaming from s3 to ios devices

I am new to ios development and creating the application which will stream videos from amazon s3 to ios device moreover I store videos in mp4 format.Can I directly stream mp4 videos from s3 to ios?if so how can I start to achieve it.

Non-renewing subscription end date

I'm developing an iOS app with a non-renewing subscription. We want to use MKStoreKit to handle everything related with IAP. My understanding is that we've to manage "manually" when the subscription is finished in order to don't show the premium contents to the users.

  • How can this be done if nothing is stored in our servers?
  • Can we check (somehow with MKStoreKit) the subscription date in order to calculate the ending date?
  • If users have several devices, we guess we'll need to implement the "restore" method so all the devices will be able to see the premium contents, no?
  • And what happens if once the first subscription is over, a user decides to subscribe again? Will we know both beginning dates? just the last one?

Thanks!

Converting tethered jailbreak into untethered jailbreak?

Hello is it possible to convert a downgraded iphone 4 (tethered) into a untethered jailbreak with saving of shsh blobs? Or there any other ways to make it possible? ios on the iphone 4 is horrible.

SpriteKit move physics body on touch (air hockey game)

I'm trying to make an air hockey game using SpriteKit. I trying to make the pucks draggable but I can't make them continue to move after the touch has ended. Right now I am binding the touch and the puck and setting it's position when the touch moves.

iPhone OS does not match app deployment version

I am using the Xcode 7.0 beta, trying to use iBeacon thing. I don't have developer account, but heard the beta can run apps on your device. But when I was trying to run the program, device OS version is lower than deployment target my phone is iPhone 5 ios 8.4 which is the most new version. however the deployment target is IOS 9.0. How can i fix this problem.

iOS best practice to display errors for a uitableview after pull to refresh and/or scroll to load more

I've recently developed an android app and used toasts to display any errors (network or web service errors) that may have happened when pulling to refresh or scrolling to load more in a table. They were great at displaying these errors without being to invasive or requiring user input to remove.

Seeing as iOS doesn't have a toast equivalent I wanted to know what are considered best practices on iOS to display errors when pulling to refresh or scrolling to load more in a UITableView.

Personally a UIAlertView seems a bit to invasive and requires a user input to remove, but I could be wrong and that may be the standard on iOS. I'm not opposed to using libraries out there that have implemented toast like views, but I figured I'd check if there was a better way since it's not built in.

Any suggestions on this would be great. Thanks!

How to sign out with Google+ on iPhone

I am writing an application where user can login using Google+. I followed GOOGLE Developer console and successfully logged in and obtained the user profile information through Access_Token. and i want to login through web view, but how to make sign out after login?

My Webview method

-(void)addWebView
{

    NSString *url = [NSString stringWithFormat:@"http://ift.tt/Kyk9ty",client_id,callbakc,scope,visibleactions];

    self.webview = [[UIWebView alloc]init];
    self.webview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    self.webview.delegate = self;
    [self.view addSubview:self.webview];
    [self.webview  loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];


}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    //    [indicator startAnimating];
    if ([[[request URL] host] isEqualToString:@"localhost"]) {

        // Extract oauth_verifier from URL query
        NSString* verifier = nil;
        NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"];
        for (NSString* param in urlParams) {
            NSArray* keyValue = [param componentsSeparatedByString:@"="];
            NSString* key = [keyValue objectAtIndex:0];
            if ([key isEqualToString:@"code"]) {
                verifier = [keyValue objectAtIndex:1];
                NSLog(@"verifier %@",verifier);
                break;
            }
        }

        if (verifier) {
            NSString *data = [NSString stringWithFormat:@"code=%@&client_id=%@&client_secret=%@&redirect_uri=%@&grant_type=authorization_code", verifier,client_id,secret,callbakc];
            NSString *url = [NSString stringWithFormat:@"http://ift.tt/IlrJjr"];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
            NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
            receivedData = [[NSMutableData alloc] init];

        } else {
            // ERROR!
        }

        [webView removeFromSuperview];

        return NO;
    }
    return YES;
}

Replay button doesn't work. (Swift, SpriteKit)

Once my game ends, it displays a button for replay, but I can't understand how to let Xcode know if there is a touch after the game has ended. My replay button's code is in didBeginContact Method and is as follows:

func didBeginContact(contact: SKPhysicsContact) {
       if (.....) {
            ..........
      }  else {
         replayButton = SKSpriteNode(imageNamed: "ReplayButton")
            replayButton.position = CGPoint(x: size.width / 1.75, y: size.height / 2.5)
            replayButton.name = "replayButton"
            self.addChild(replayButton)
       }

New Swift file:

class button: Mode {


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

var touch = touches as!  Set<UITouch>
var location = touch.first!.locationInNode(self)
var node = self.nodeAtPoint(location)


if (node.name == "replayButton") {

    let myScene = EasyMode(size: self.size)
    myScene.scaleMode = scaleMode
    let reveal = SKTransition.fadeWithDuration(2.0)
    self.view?.presentScene(myScene, transition: reveal)
    }
  }
}

How i can play [UInt8] audio stream?

I am connected to the server via TCP / IP and receives [UInt8]. I know that it is the audio. How to play the stream on the iPhone?

Constraints for buttons between all device sizes xcode 7

I have three buttons laid out like this in Xcode: http://ift.tt/1DquD8w

As you can see, I have errors for my constraints within my storyboard. I used constraints from a picture that someone from here on stack overflow drew up for me:

http://ift.tt/1Ul0Xyc

I've tried many other constraints but I can't seem to figure out what constraints to use.

How can I fix this so it looks like it does in the storyboard across all iPhones and iPads? Landscape mode will not be a part of this application.

How to change the duration of a movement with count- Swift SpriteKit?

In my game, there's a class for a "wall" that's moving to the left. I want to change the speed of it based on count i that I added to touchesBegan method:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent {
    count++
}

func startMoving() {

    let moveLeft = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 1 )

    let move = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 0.5)

    if(count <= 10)
    {
        runAction(SKAction.repeatActionForever(moveLeft))
    }
    else
    {
    runAction(SKAction.repeatActionForever(move))
    }
}

but it's not working. Can you help?

How can I save video to photo library?

I copied this code from a book and arrange it to my code but I have doubts how to save the videos that I'm recording. Do I need to take the video URL? if so, how can I take it? Thanks

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as? NSString

    self.dismissViewControllerAnimated(true, completion: nil)

    if mediaType == (kUTTypeImage as! String) {
        let image = info[UIImagePickerControllerOriginalImage] as? UIImage

        imageView.image = image

        if (newMedia == true) {
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        } else if mediaType == (kUTTypeMovie as! String) {
            //Code to support video


        }

    }
}

Segue from Container View

I am trying to create a segue from a container view (left VC) to a view controller (right VC). I want to be able to click on a person, who will be displayed on the left VC, and chat with him on the right VC. The thing is when I create the segue, the VC on the right instantly becomes the same size as the container view and gains the tab bar/navigation bar that the container view has. It there any way I can connect the container view with the new VC and making the new VC an independent one? Thanks

enter image description here

Swift iOS static uitableviewheader

I wonder if its possible to add a static uitableviewheader? I want the header to look like an extension of the navigation bar. But I can't get it to work, my header keeps scrolling with the table view.

Push messages longer than 255 characters not reaching iPhone

I'm trying to send a push notification to a device - which is longer than 255 characters.

I'm not getting any errors from Apple servers but the push notification does not reach my device.

  1. Using Pusher (http://ift.tt/M5cofk) the push notification DOES reach the device - using the same certificate.
  2. Sending a push notification smaller than 255 characters DOES reach the device

What could be the issue?

iOS autolayout issue

i am using xcode 6.4. i have a view controller named "sample".The view controller contain a scroll view.The scrollview contain another view(container view).The width of container view is thrice of the width of scrollview.when the scroll view is swiping right(or left) it must show the 3 parts of the container view.I did it using paging enabled property of UIscrollview(without auto-layout).But when using auto-layout i cant find a solution.Can anybody tell me a solution for this???please explain constraints for scroll view and container view.Can anybody upload a demo???

what is typedef long dispatch_once_t in objective c [duplicate]

This question already has an answer here:

i was going through this tutorial, and i noticed they used:

typedef long dispatch_once_t

yet they did not explain what it does. Furthermore, I have no idea what does "typedef long" mean ? i tried searching through references but didnt find an answer. Can you provide an example of how typedef long works ?

JSON parsing using [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error] thowing nil

error = Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7fa4e25da7c0 {NSDebugDescription=Garbage at end.}

If changing NSData to NSString , response is getting but using

id jsonData = [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error]

showing above error, and response nil.

How to force or disable interface orientation for some but not all UIViewController?

I have an app with 9-10 screens. I embedded a UINavigationController into my view controller. I have few view controllers which I want set only portrait orientation: it means that rotating the device should not rotate these view controllers to landscape mode. I have tried the following solutions:

first:

   NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
   [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

but screen still rotates to landscape.

Second: I created a custom view controller class as PortraitViewController and added the code below in PortraitViewController.m

@interface PortraitViewController ()
@end

@implementation PortraitViewController
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    //Here check class name and then return type of orientation
    return UIInterfaceOrientationMaskPortrait;
}
@end

After that I implemented PortraitViewController.h as a base class

#import <UIKit/UIKit.h>
#import "PortraitViewController.h"
@interface Login : PortraitViewController
@end

It does not work at all, still allows view controller to rotate in landscape mode.

Is there any other solution i am using iOS 8 & don't want viewcontroller to rotate in landscape mode?

EDIT: Is it possible to have Landscape orientation only for some view controllers, and force other view controllers orientation to stick to Portrait?

Generating Random Numbers of a certain pattern in Swift

I know that Swift can generate random numbers using this code : arc4random_uniform(50). So how can I generate random numbers in a pattern, for example : The computer should generate random numbers in the order 2,8,9,15,16,22... like any number x,x+6,x+6+1,x+6+1+6.... like that. Please help soon..! It would be a great help !

iOS keep app always alive, disable scree

I'm building home automation system for my house. The plan is to have lots of different rfduino nodes taking to one wall mounted iPad through the bluetooth.

So far all working perfect apart from keeping an app alive all the time, device is plugged to the charger.

My question is rather simple and I struggle to find a solution. How can I keep the app always alive to do its processing but with the disabled screen?

Thanks in advance

Open iCloud drive programatically

I'm using CloudKit in my app and I want to send the user to iCloud settings in case he/she hasn't enabled or set it up. I am currently using the following code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

But it opens the following:

enter image description here

So the user would have to go back and look for iCloud to set it up, how can I redirect the user directly to iCloud settings?

Thanks in advance!

EAAccessoryManager connectedAccessories returns empty array

I am using EAAccessoryManager to connect my application to a MFI accessory. During the initial connection, in bluetooth setting screen, it showing as device connected. When i try to get the list of connected device using "[accessoryManager connectedAccessories]", it returns a empty array. But when i use "showBluetoothAccessoryPickerWithNameFilter", it shows me the accessory in the list. The problem is i don't want user to choose the accessory. I want to make this a automated process. I have included the accessory protocol string in info.plist too. Please guide me with this issue. What mistake i am doing here ?

Swift possible to add view under navigation bar in UITableViewController

I wonder if its possible to add a view under the navigation bar in a UITableViewController?

What I would like to do is to add a view under the navigation bar in my UITableViewController so that I can add a search input / filter button to that view. But I want the view to have a fixed position under the navigation bar so that I can hide the navigationbar+view when swiping.

Right now storyboard only lets me add a view in the UITableViewController. And the new view is also swipeable. And the loading indicator shows up above the view when you swipe down.

enter image description here

how to get directions between two places in iOS

MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:@""];

MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:@""];

MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeAny];

MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {

    NSLog(@"response = %@",response);
    NSArray *arrRoutes = [response routes];
    [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        MKRoute *rout = obj;

        MKPolyline *line = [rout polyline];
        [mapview addOverlay:line];
        NSLog(@"Rout Name : %@",rout.name);
        NSLog(@"Total Distance (in Meters) :%f",rout.distance);

        NSArray *steps = [rout steps];

        NSLog(@"Total Steps : %lu",(unsigned long)[steps count]);
        NSMutableArray *stepsArray=[[NSMutableArray alloc] init];
        [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"Rout Instruction : %@",[obj instructions]);
            NSLog(@"Rout Distance : %f",[obj distance]);
            [stepsArray addObject:[obj instructions]];
        }];

        [self myShowDirections:response];
        self.steps.text=[NSString stringWithFormat:@"%@",stepsArray];

i am using this code but it gives using latitude and longitude.but i want to get directions for searching by the to address and from address.please help me anyone?Thanks in advance.

How to scroll the textfields when view is moved up?

I have text fields on registration screen so when keyboard appears i am moving up the view up.Now i want to scroll through text fields when i my view is moved up.

code for moving view up:

         CGRect rect = self.view.frame;
         rect.origin.y += 220;
         rect.size.height -= 220;
         self.view.frame = rect;

Here is hirecrchy

I have UIScrollView at top then under UIScrollView i have UIView i call it as contentView.On the contentView i have added some text fields.So my parent view is moved up fine but i am not able to scroll the textFields up & down when i view is up. I set the following value for scrolling.

    self.cvHeight.constant=500;
    self.scrollView.contentSize=CGSizeMake(500, 500);

Here cvHeight is outlet of height constraint of the contentView & scrollView is outlet of UIScrollView

Edit: When i am not moving the parentView up which is self.view then i am able to scroll through but if i move the parent view up then my textFields are not scrolling down they are just moving up.

this is my i am gitting error why any one tell me they can give me error

NSMutableDictionary *inputData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self.usertext text], @"username", [self.passwordtext text], @"password", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:inputData options:0 error:nil];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dict = @{@"body":json};
NSLog(@"JSOND: %@", dict);
NSLog(@"JSON: %@", json);
// Create a Request with the given URL
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"bearer null" forHTTPHeaderField:@"Authorization"];

[manager POST:@"http://ift.tt/1OSE5TF" parameters:dict success:^
 (AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"operation: %@", operation);
     NSLog(@"Response: %@", responseObject);
    }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSString *myString = [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding];
    NSLog(@"Error: %@", myString);
}];

invalid nib registered for identifier (DeviceLostPhotoCell) - nib must contain exactly one top level object which must be a UITableViewCell instance

I'm trying to create a custom cell for my table. This custom cell must have a collection horizontal view inside. I did the configuration of the collection view with the delegate and datasource and add the necessary methods. Now I am getting the following error:

"reason: 'invalid nib registered for identifier (DeviceLostPhotoCell) - nib must contain exactly one top level object which must be a UITableViewCell instance'"

this is my code:

- (void)awakeFromNib {
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section; {
    return 5;
}

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

    return cell;
}

this red square this with the identifier "DeviceImageCell" what should be the cell of my collection view.

this red square this with the identifier "DeviceImageCell" what should be the cell of my collection view.

How to get the folder details for a mail using messageID?

I am using Mailcore2 to fetch mails from IMAP server. If I have a messageID of a mail using that can I get the folder in which it is for Outlook and Yahoo mails? Thanks for any help.

iOS spotlight icon won't show

For my app icon I have crossed Iphone: iOS 8 and later and iOS 7 and later and ipad: iOS 7 and later then I transferred all 12 icons but when I do a spotlight search in my iphone the icon won't show up. Have I missed something?

Also, what does iOS icon is pre-renered option mean and do I need it?

Thanks