dimanche 10 mai 2015

Debug on Apple Watch: Error Launching 'xxx WatchKit Extension' - Couldn’t communicate with a helper application

I am trying to debug on my apple watch (real device, not simulator). My main project runs on my iPhone fine, and the corresponding watch app shows up on my watch. I want to attach the debugger to my watch app, so in Xcode I choose WatchKit App scheme, then choose my iPhone. I hit the run button, and an error window pops up, with title Error Launching 'xxx WatchKit Extension' and description Couldn’t communicate with a helper application.

Both my main app and watch app run fine if I build and run by choosing the main app scheme, however I wish to attach the debugger to my watch app scheme. Does anyone know what might be causing this error? Thanks in advance.

Xcode 6 Crash on Launch error EXC_BAD_ACCESS (SIGSEGV)

Process:               Xcode [3797]
Path:                  /Applications/http://ift.tt/1kAnkB8
Identifier:            com.apple.dt.Xcode
Version:               6.3.1 (7703)
Build Info:            IDEFrameworks-7703000000000000~4
App Item ID:           497799835
App External ID:       812230896
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [3797]
User ID:               501

Date/Time:             2015-05-10 18:38:38.606 -0400
OS Version:            Mac OS X 10.10.3 (14D136)
Report Version:        11
Anonymous UUID:        00D6503E-DBD7-2FE7-3ECF-A8EF678DFC38

Sleep/Wake UUID:       2788F068-DB50-4E00-9B74-E4FC95AC2582

Time Awake Since Boot: 26000 seconds
Time Since Wake:       1700 seconds

Crashed Thread:        7  Dispatch queue: com.apple.dt.Xcode.IBSourceCodeClassProvider

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000000

VM Regions Near 0:
--> 
    __TEXT                 0000000109d67000-0000000109d68000 [    4K] r-x/rwx SM=COW  /Applications/http://ift.tt/1kAnkB8

Application Specific Information:
ProductBuildVersion: 6D1002

Thread 0:: Dispatch queue: com.apple.main-thread
0   libobjc.A.dylib                 0x00007fff8b34e0d8 search_method_list(method_list_t const*, objc_selector*) + 58
1   libobjc.A.dylib                 0x00007fff8b35fa21 getMethodNoSuper_nolock(objc_class*, objc_selector*) + 89
2   libobjc.A.dylib                 0x00007fff8b35f89b lookUpImpOrForward + 614
3   libobjc.A.dylib                 0x00007fff8b35f617 lookUpImpOrNil + 20
4   libobjc.A.dylib                 0x00007fff8b359970 _class_resolveInstanceMethod(objc_class*, objc_selector*, objc_object*) + 108
5   libobjc.A.dylib                 0x00007fff8b35f799 lookUpImpOrForward + 356
6   libobjc.A.dylib                 0x00007fff8b352408 class_getInstanceMethod + 60
7   com.apple.Foundation            0x00007fff9205920c NSKeyValueMethodForPattern + 139
8   com.apple.Foundation            0x00007fff92059d89 +[NSObject(NSKeyValueCodingPrivate) _createValueGetterWithContainerClassID:key:] + 319
9   com.apple.Foundation            0x00007fff92059bc8 -[NSObject(NSKeyValueCoding) valueForKey:] + 270
10  com.apple.dt.IDEKit             0x000000010b012249 -[IDENavigableItem childItems] + 111
11  com.apple.dt.IDEKit             0x000000010b020d9a -[IDEFileNavigableItem identifierForChildItem:] + 154
12  com.apple.dt.IDEKit             0x000000010b0206a6 -[IDENavigableItemArchivableRepresentation initWithNavigableItem:] + 368
13  com.apple.dt.IDEKit             0x000000010b03081f -[IDENavigableItem archivableRepresentation] + 50
14  com.apple.dt.IDEKit             0x000000010b1d8093 -[IDEEditorArea selectedNavigableItemArchivedRepresentation] + 106
15  com.apple.dt.IDEKit             0x000000010b17b521 __50-[IDENavigatorArea _handleCurrentNavigatorChanged]_block_invoke + 87
16  com.apple.dt.DVTFoundation      0x0000000109eb45c8 -[_DVTAsynchronousRequest _invokeBlock:] + 58
17  com.apple.Foundation            0x00007fff9207c41b __NSFireDelayedPerform + 364
18  com.apple.CoreFoundation        0x00007fff8e2682e4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
19  com.apple.CoreFoundation        0x00007fff8e267f73 __CFRunLoopDoTimer + 1059
20  com.apple.CoreFoundation        0x00007fff8e2db53d __CFRunLoopDoTimers + 301
21  com.apple.CoreFoundation        0x00007fff8e223608 __CFRunLoopRun + 2024
22  com.apple.CoreFoundation        0x00007fff8e222bd8 CFRunLoopRunSpecific + 296
23  com.apple.HIToolbox             0x00007fff90a0956f RunCurrentEventLoopInMode + 235
24  com.apple.HIToolbox             0x00007fff90a092ea ReceiveNextEventCommon + 431
25  com.apple.HIToolbox             0x00007fff90a0912b _BlockUntilNextEventMatchingListInModeWithFilter + 71
26  com.apple.AppKit                0x00007fff931149bb _DPSNextEvent + 978
27  com.apple.AppKit                0x00007fff93113f68 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 346
28  com.apple.dt.DVTKit             0x000000010a4badda -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 237
29  com.apple.AppKit                0x00007fff93109bf3 -[NSApplication run] + 594
30  com.apple.AppKit                0x00007fff93086354 NSApplicationMain + 1832
31  libdyld.dylib                   0x00007fff964605c9 start + 1

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff96456232 kevent64 + 10
1   libdispatch.dylib               0x00007fff96bafa6a _dispatch_mgr_thread + 52

Thread 2:
0   libsystem_kernel.dylib          0x00007fff9645594a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8e19440d start_wqthread + 13

Thread 3:
0   libsystem_kernel.dylib          0x00007fff9645594a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8e19440d start_wqthread + 13

Thread 4:
0   libsystem_kernel.dylib          0x00007fff9645594a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8e19440d start_wqthread + 13

Thread 5:: Dispatch queue: IBPlatformToolRequestQueue.IBCocoaTouchFramework-EightAndLater
0   libsystem_kernel.dylib          0x00007fff96456682 read + 10
1   com.apple.dt.IBFoundation       0x0000000110b15c13 -[IBMessageSendChannel sendMessage:returnValue:context:error:arguments:] + 1252
2   com.apple.dt.IDE.IDEInterfaceBuilderKit 0x0000000115397ef0 -[IBAbstractMessageChannelInterfaceBuilderToolProxy renderImagesForRequests:] + 228
3   com.apple.dt.IDE.IDEInterfaceBuilderCocoaTouchIntegration   0x000000011a239625 0x11a0b5000 + 1590821
4   com.apple.dt.IDE.IDEInterfaceBuilderKit 0x00000001153dba79 -[IBRemoteViewImageRequestProcessor performRequestOnBackgroundThreadWithData:platformTool:] + 89
5   com.apple.dt.IDE.IDEInterfaceBuilderKit 0x0000000115231ccb -[IBPlatformToolRequester processRequests] + 1079
6   com.apple.dt.DVTFoundation      0x0000000109f72cbc __DVTDispatchAsync_block_invoke + 106
7   libdispatch.dylib               0x00007fff96bb1323 _dispatch_call_block_and_release + 12
8   libdispatch.dylib               0x00007fff96bacc13 _dispatch_client_callout + 8
9   libdispatch.dylib               0x00007fff96bb0365 _dispatch_queue_drain + 1100
10  libdispatch.dylib               0x00007fff96bb1ecc _dispatch_queue_invoke + 202
11  libdispatch.dylib               0x00007fff96baf6b7 _dispatch_root_queue_drain + 463
12  libdispatch.dylib               0x00007fff96bbdfe4 _dispatch_worker_thread3 + 91
13  libsystem_pthread.dylib         0x00007fff8e196637 _pthread_wqthread + 729
14  libsystem_pthread.dylib         0x00007fff8e19440d start_wqthread + 13

XCODE crashes on launch.. please help! I've reinstalled Xcode, deleted .userdata and even tried to remake the project by transferrin the existing files, but the new project yields the same error.

seems to be a corruption issues somehow following these specific files, but need to retrieve them.. thanks in advance!

avkit player swift xcode - Looking for a tutorial

I simply want to make something very similar to the Headspace iOS app. I think I can get mostly there but I simply can't figure out where to begin in order to have two main elements - a button that is pressed and plays a video or audio. A tutorial or simple explanation would be great if anybody has encountered one or thinks it's simple to achieve.

Any help would be greatly appreciated.

xcode 6.3

Using storyboard and auto-layout to position buttons by screen percentage

I'm trying to set up some constraints inside a view via storyboard (im not a fan of contrasting via code). My main goal is kinda simple, but tricky : How can i align 3 buttons by PERCENTAGE using Multiplier inside a view?

Example : What do we see? 3 buttons inside a view. The left button is 10% from the view width(from his left side). The second one is centered , and the third one is 10% from the right side.

source

What am i trying to do?

I want to accomplish this using only Horizontal Center in Container and Vertical Center in Container through their Multiplier

What have i done so far?

Until now i tried using trailing and leading spaces constraints, the problem is that its not relative to the view size. Any suggestions guys? I'm trying to figure this out for the last few days.

How to make arabic HTML on macbook?

Does anyone know how to make an arabic html page it in mac?

It has been easily managed in Windows but since I got the macbook I have been stuck

using Text editor, it is not working as simple as notepad, the arabic page doesn't display as it used to on windows

using xcode, the encoding is ruined in the displayed page

I am using the meta tag in the head part for UTF-8 \ and that was enough when I was using notepad on windows beside making sure that notepad encoding is unicode.. but the same steps are not enough on macbook

any solutions please

Xcode project send from freelancer, won't run, says ''build failed''

I just received my iphone app in a xcode file from my freelancer. When i open the project in xcode and clicks ''run'' it says ''build failed'' and i get the following message

http://ift.tt/1cmWeeg

How do i fix this? I am new to xcode and need a detailed description of how to do it.

UITextField not displaying NSFontAttributes

I'm writing in Swift, have an app that includes multiple user-editable textFields and textViews, all with attributedText editing features.

Once edited, information is saved to a CoreData object as well as uploaded to a server for backup. The server saves the AttributedStrings as HTML, and it is converted back to NSAttributedString when downloaded/synced.

All of this works (although I get a lot of extra attributes like paragraph style added), but for some reason, my textFields, once saved and re-loaded, don't display any italic or bold font attributes (even though it exists, is uploaded, downloaded, and converted just fine). Yet the textViews, going through the same process, display the text just fine.

Any idea why a textField would not work and a textView does for displaying attributed text?

Here's some code, I can add more if I'm missing something necessary:

Sample HTML field text:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ift.tt/nYkKzf">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px Optima; color: #000000; -webkit-text-stroke: #000000}
span.s1 {font-family: 'Optima'; font-weight: bold; font-style: normal; font-size: 16.00pt; font-kerning: none; text-shadow: 0.0px -1.0px 0.0px rgba(255, 255, 255, 0)}
span.s2 {font-family: 'Optima-Regular'; font-weight: normal; font-style: normal; font-size: 16.00pt; font-kerning: none; text-shadow: 0.0px -1.0px 0.0px rgba(255, 255, 255, 0)}
span.s3 {font-family: 'Optima'; font-weight: normal; font-style: italic; font-size: 16.00pt; font-kerning: none; text-shadow: 0.0px -1.0px 0.0px rgba(255, 255, 255, 0)}
span.s4 {font-family: 'Optima-Regular'; font-weight: normal; font-style: normal; font-size: 16.00pt; text-decoration: underline ; font-kerning: none; text-shadow: 0.0px -1.0px 0.0px rgba(255, 255, 255, 0)}
</style>
</head>
<body>
<p class="p1"><span class="s1">Check</span><span class="s2"> </span><span class="s3">for</span><span class="s2"> </span><span class="s4">title</span><span class="s2"> here. <span class="Apple-converted-space">Â  Â </span></span></p>
</body>
</html>

NSAttributeString / HTML Converters:

class AttrTextConverter {
func toHtmlString(attrString: NSAttributedString) -> String {
    if let toData = attrString.dataFromRange(NSMakeRange(0, attrString.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], error: nil) {
        let htmlNSString = NSString(data: toData, encoding: NSUTF8StringEncoding)
        let htmlString = htmlNSString as! String
        return htmlString
    }
    return ""
}

func toAttrString(htmlString: String) -> NSAttributedString {
    let htmlNsString = htmlString as NSString
    let htmlData = htmlNsString.dataUsingEncoding(NSUTF8StringEncoding)
    var concreteString : NSAttributedString = NSAttributedString(string: "")
    if let attrString = NSMutableAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil) {
        attrString.enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions.allZeros) { value, range, stop in
            if value != nil {
                let oldFont = value as! UIFont
                let oldName = oldFont.fontName
                var newFont = defaultFont
                if oldName.hasSuffix("-BoldOblique") || oldName.hasSuffix("-BoldItalic") {
                    newFont = defaultBoldItalic
                } else if oldName.hasSuffix("-Bold") {
                    newFont = defaultBold
                } else if oldName.hasSuffix("-Italic") || oldName.hasSuffix("-Oblique") {
                    newFont = defaultItalic
                }
                attrString.removeAttribute(NSFontAttributeName, range: range)
                attrString.addAttribute(NSFontAttributeName, value: newFont, range: range)
            } else {
                attrString.addAttribute(NSFontAttributeName, value: defaultFont, range: NSMakeRange(0, attrString.length))
            }
        }
        concreteString = attrString
    }

    return concreteString
}
}

And this is the display code in the viewController:

textView (WORKS):

if let mutStr = lesson?.valueForKey(record) as? NSAttributedString {
                let newStr = fontSet.changeFontFamily(mutStr)
                view.attributedText = newStr
            }

textField (DOESN'T WORK):

if let mutStr = lesson?.valueForKey(record) as? NSAttributedString {
                let newStr = fontSet.changeFontFamily(mutStr)
                field.attributedText = newStr
            }

How to add youtube videos to custom uitableviewcell using uiwebview

i'm new to iOS development. i would like to display few webpages using uiwebview and a label which are on a custom table cell i've succeeded in getting different names for different cell but getting same url in each custom cell. how can i get different URLs for different cell ![enter image description here][1]

How to implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods

I'm trying to follow the instructions from this post How to zoom in/out an UIImage object when user pinches screen? but I don't know how to implement these methods. I know that is a basic question but if anyone could take a minute to help a beginner I would greatly appreciate it thanks!

Edit: I don't know what goes in the () for the viewForZoomingInScrollView method. My error is unresolved identifier 'viewForZoomingInScrollView'.

This stuff is incredibly difficult to figure out for a beginner... is there an easier way to learn coding??

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!



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

    scrollView.delegate = self

    viewForZoomingInScrollView(UIScrollView:scrollView) {

        return self.ImageView;

    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Testflight iOS Minimum Requirement different than XCode

In xcode my project's iOS deployment target is 8.0 (in both the build settings and the general target info) yet when it uploads to testflight it changes to 8.3 as the minimum requirement. Is there another setting I'm missing? Thanks

Xcode 5.1 crashing when i try to open .xib file

I am using xcode 6.1.I have created App using Autolayout.I wanted to test the app on ios6 so i Download the xcode 5.0 when i try to open .xib File xcode is crashing.

Remove iAd banner from just 1 scene

I have a basic game created with 3 scenes - Start, GameScene and Gameover Scene. I implemented iAd banners very easily using the below code. This was super simple for me as a beginner to do, however the banner ad seems to be impacting the frame rate during game play so I want it to be removed/hidden during the game scene. Is there any easy way to do this ?

override func viewDidLoad() {

       super.viewDidLoad()
      self.canDisplayBannerAds = true

How to set multiple variables in a FOR loop?

I'm programming in Swift and I'd like to set up a couple of variables in a single loop. These are UIButtons and they all require the same settings. However I don't know how to refer to these variables using "i". This is what I tried:

var gg1:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var gg2:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var gg3:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

//further in the code
for i in 1...3 {
    gg(i).layer.anchorPoint.x = 0
    gg(i).titleLabel?.font = UIFont(name: "Arial", size: 20*rightFontSize)
    gg(i).setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
    gg(i).sizeToFit()
    gg(i).center = CGPointMake(w/20,11*h/10)
    scrollView.addSubview(gg(i))
}

Viewing an array and tuple in Xcode 6.3 Playground

Prior to Xcode 6.3 when I clicked the Quick Look icon on the left in Playground file, it showed the array along with item indexes. Now it shows only "X elements" text and nothing else. Same thing happened with tuples. It's quite annoying since not always all elements fit in the sidebar. How to fix this?

Android material animations in ios cocoa touch

Apologies for the generic question however I am in need of some guidance so that I can do further reading.

The question is:

Is it possible to do UI transitions similar to android material UI transitions in IOS Cocoa touch? Can core graphic or core animation do complex shape tweening like flash (not just animating simple properties such as opacity or size.

For example please have a look at the following link: http://ift.tt/1EtHReD

How can such animation effects be accomplished in cocoa touch?

Any pointers would be useful so that I can do further reading.

Many thanks

UIImage not rendering in Xcode 6.3.1 Playground

I spent two hours trying to make this simple code to work, with no luck.

What I did:

  • I put a resource in the Resources directory.
  • I referenced the resource as UImage(named: "resource.jpg")

However, nothing is showing up. Here's a snapshot of my screen. As you can see there's no playground indicator running.

enter image description here

swift how make animation flip between two UIViews

I'm trying to create an IOS app and flip two views when pressing some buttons. I have found the flip animation but I want the flip to change the content to the new view when it is flipped 90° and not when the animation is completed. This is my function:

func animationFlip(fromView:UIView, toView:UIView, animationTime:Float)
{

    UIView.animateWithDuration(NSTimeInterval(animationTime), animations: {

        UIView.setAnimationTransition(UIViewAnimationTransition.FlipFromRight, forView: fromView, cache: true)

        },completion:{completion in
            UIView.animateWithDuration(NSTimeInterval(animationTime), animations: { () -> Void in

                fromView.hidden = true;
                toView.hidden = false;
                UIView.setAnimationTransition(UIViewAnimationTransition.FlipFromRight, forView: toView, cache: true)


            })
    })
}

I have found this code which seems to do the trick but it is written in obj-c. How can it be translated to swift?

[UIView transitionFromView:viewToReplace
        toView:replacementView
        duration:1
        options:UIViewAnimationOptionTransitionFlipFromBottom
        completion:nil];

Thanks in advance!

How to remove iPhone 4s and lower compatibility from Xcode project

iTunes Connect always asks me for 3.5 inch snapshots, how can I get rid of it?

How to present a new viewController without a action?

Im trying to push to a new viewController if a user is logged in, but I don't really understand were it fails or how the best why of presenting a viewController.

how can i set the window hierarchy? or push a viewController programmatically without a button action?

    if (FBSDKAccessToken.currentAccessToken() != nil)
    {
        returnUserData()
        var storyboard: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)

        var vc: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("loggedInViewController") as! UINavigationController

        self.presentViewController(vc, animated: true, completion: nil)
        // User is already logged in, do work such as go to next view controller.
    }

error message:

User Logged In 2015-05-10 16:35:18.010 noscrubs[32134:43488091] Warning: Attempt to present on whose view is not in the window hierarchy!

thanks a lot for any help I really want to get into the flow, so all pointers are appreciated!

UITableView in Swift: Offscreen cells are not pre-loaded

I have a little problem with UITableView. Cells that are offscreen are not loaded when I first scroll down. When I scroll up (so that the not showing cells are offscreen again) and scroll down again they suddenly show up. I think this has something to do with dequeueReusableCellWithIdentifier. Any idea how to fix this?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCellClass
return cell

Login screen - button to next segue

I've looked at a view other methods but not found one to do what I want and the ones that do carry out the task don't work for me.

I have 3 fields, all which require data to be entered to proceed to the next view, but it doesn't seem to work.

This is my code so far;

@IBOutlet weak var campustext: UITextField!
@IBOutlet weak var usernametext: UITextField!
@IBOutlet weak var passwordtext: UITextField!
@IBOutlet weak var loginlabel: UILabel!


@IBAction func loginbutton(sender: AnyObject){
    var campus = "Magee"
    var username = "B00123456"
    var password = "Password"

    if  campustext.text == campus &&
        usernametext.text == username &&
        passwordtext.text == password
    {
       let segueShouldOccur = true


    }

    else

    {
        loginlabel.text = "Oops..something went wrong. Please try again."
        println("Credentials were not correct")
        let segueShouldOccur = false


    }
}




override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
    if identifier == "mainview" {
        // perform your computation to determine whether segue should occur


        let segueShouldOccur = true || false // you determine this
        if !segueShouldOccur {
            let notPermitted = UIAlertView(title: "Alert", message: "Segue not permitted (better message here)", delegate: nil, cancelButtonTitle: "OK")

            // shows alert to user
            notPermitted.show()

            // prevent segue from occurring
            return false
        }
    }



    // by default perform the segue transitio
    return true
}


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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

If anyone can help, would really appreciate it!

Error message When submitting to apple App store

when trying to submit my app on iTunes i keep getting this error. How do i fix it??

error ITMS-90017: "this bundle is invaild. The IPA format requires a top-level directory named payload, containting only a. app bundle and optional plugins in a Plugins directory"

How to make clock ticks stuck to the clock border?

I try to make a clock, in swift, but now i want to make something strange. I want make border radius settable. This is the easy part (is easy because I already did that). I drew 60 ticks around the clock. The problem is that 60 ticks are a perfect circle. If I change the border radius I obtain this clock:

enter image description here

All ticks are made with NSBezierPath, and code for calculate position for every tick is :

tickPath.moveToPoint(CGPoint(
            x: center.x + cos(angle) *  point1 ,
            y: center.y + sin(angle) * point1
            ))

        tickPath.lineToPoint(CGPoint(
            x: center.x + cos(angle) * point2,
            y: center.y + sin(angle) * point2
            ))

point1 and point2 are points for 12 clock tick.

My clock background is made with bezier path:

 let bezierPath = NSBezierPath(roundedRect:self.bounds, xRadius:currentRadius, yRadius:currentRadius) 

currentRadius - is a settable var , so my background cam be, from a perfect circle (when corner radius = height / 2) to a square (when corner radius = 0 ).

Is any formula to calculate position for every tick so, for any border radius , in the end all ticks to be at same distance to border ?

Why are there trailing slashes in NSURL constructed from initWithScheme ...?

When using the NSURL constructor

initWithScheme:(NSString *) host:(NSString *) path:(NSString *)

iOS for some reason appends two extra trailing slashes if the path ends with a slash, unless it's only @"/".

enter image description here

Does anyone know why this is, and if there's a way around it other than composing the url manually with something like

[NSURL URLWithString:[NSString stringWithFormat:@"%@://%@%@", scheme, host, path]];

How do I switch views after signing up and logging in?

So the backend is working, I can successfully create accounts and login. Now I want them to transition to the home screen so how I do I set so if the sigup/login is successful it transitions? This is my code:

- (IBAction)signUp:(UIButton *)sender {


NSString *name      = _textUsername.text;
NSString *password  = _textPassword.text;
NSString *email     = [_textEmail.text lowercaseString];
//---------------------------------------------------------------------------------------------------------------------------------------------
if ([name length] == 0)     { [ProgressHUD showError:@"Name must be set."]; return; }
if ([password length] == 0) { [ProgressHUD showError:@"Password must be set."]; return; }
if ([email length] == 0)    { [ProgressHUD showError:@"Email must be set."]; return; }
//---------------------------------------------------------------------------------------------------------------------------------------------
[ProgressHUD show:@"Please wait..." Interaction:NO];

PFUser *user = [PFUser user];
user.username = name;
user.password = password;
user.email = email;
user[PF_USER_EMAILCOPY] = email;
user[PF_USER_FULLNAME] = name;
user[PF_USER_FULLNAME_LOWER] = [name lowercaseString];
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
 {
     if (error == nil)
     {
         ParsePushUserAssign();
         [ProgressHUD showSuccess:@"Succeed."];
         [self dismissViewControllerAnimated:YES completion:nil];
     }
     else [ProgressHUD showError:error.userInfo[@"error"]];
 }];

Also any idea why my text field doesn't automatically go to the next one? Pretty sure the code is right. Thanks.

- (BOOL)textFieldShouldReturn:(UITextField *)textField

  {
  if (textField == _textUsername)
 {

    [textField resignFirstResponder];
    [_textEmail becomeFirstResponder];
}

else if (textField == _textEmail)
{
    [textField resignFirstResponder];
    [_textPassword becomeFirstResponder];
}

else if (textField == _textPassword)
{
    [textField becomeFirstResponder];
    [_textBirthday becomeFirstResponder];
}

else if (textField == _textBirthday)
{
 [self actionRegister];
}

return YES;

Using Audio Effects with iPhone music library

I'm trying to add some audio effects to an iPhone app I'm developing.

The app is a music player that allows users to choose songs from their iTunes music library. I want them to be able to carry some basic adjustments for example Bass, Middle, Treble and perhaps add some reverb. I've played around with NVDSP and looked at audio units however these don't seem to work with the iTunes library due to DRM restrictions.

Has anybody managed to achieve this? Thanks in Advance.

How to access a component on storyboard in my code in Xcode 6

For instance, a button is created on storyboard by drag and drop. How do I access this button and make some changes to it in my code?
I have ctrl+clicked it to create an IBOUtlet in ViewController.h.

How do I access it in ViewController.m?

A popup, "Failed to automatically update constraints" pops up in Xcode 6.3.1

When I added a couple of controls in my viewcontroller in storyboard and click Resolve Auto Layout Issues -> Reset to Suggested Constraints. The following popup appears and I cannot perform auto layout constraints.

enter image description here

Though, when I remove the Prototype Cell (which has a couple of labels and an imageview) from my tableview then auto layout works fine. Any thoughts?

Cmake Xcode project storyboard can not be loaded

I have been learning how to use CMake to generate a Xcode project. I found a nice example from http://ift.tt/1cDIfBJ. When I generate Xcode project from this testApp. I always experienced "The document "MainStoryboard_***.storyboard" could not be opened. Unrecognized file content"

I have tried that I could open MainStoryboard_***.storyboard from Xcode if I only open this storyboard without open *.xcodeproj file. I have tried to change configuration in the info.plist and cmakelists.txt files, I didn't find a solution yet.

I wonder if someone experienced this issue before,

Drag map annotation immediately without showing Callout

When tapping on my annotation I want to show a callout. That works, so far so good. If I want to drag my annotation to a different position I have to tap it first, the callout shows, and I can start dragging.

Is there a way to only show the callout on shortPress and start dragging immediately if I do a longPress?

My code for dragging:

func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {

    var liftValue:CGFloat = 40.0

    if (newState == MKAnnotationViewDragState.Starting)
    {
        var endPoint = CGPointMake(view.center.x, view.center.y - liftValue)
        UIView.animateWithDuration(0.2, animations: { () -> Void in
            view.center = endPoint
        }, completion: { (finished) -> Void in
            view.dragState = MKAnnotationViewDragState.Dragging;
        })

    }
    else if (newState == MKAnnotationViewDragState.Ending || newState == MKAnnotationViewDragState.Canceling)
    {

        var endPoint = CGPointMake(view.center.x,view.center.y - liftValue);
        UIView.animateWithDuration(0.2, animations: { () -> Void in
            view.center = endPoint
        }, completion: { (finished) -> Void in
            endPoint = CGPointMake(view.center.x, view.center.y + liftValue)
            UIView.animateWithDuration(0.1, animations: { () -> Void in
                view.center = endPoint
            }, completion: { (finished2) -> Void in
                view.dragState = MKAnnotationViewDragState.None;
            })
        })
    }
}

My annotation:

    var myPersonalView:MKAnnotationView?
    myPersonalView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)

    if (myPersonalView == nil)
    {
        myPersonalView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        myPersonalView!.canShowCallout = true
        myPersonalView!.draggable = true
    }

Litchy

Count down from date picker with Swift

I could create a count down from a number, in this case 5 and it works well. But how could I put in the label the date of the date picker and count down from that?

1- I think I could grab the selected date in the date picker.

let wakeUpTime = datePicker.date

2- Next step is to put that in the "countingLabel" and this is my next problem I could not solve. Of course, this does not work:

countingLabel.text = String(wakeUpTime)

So, my question is: how to put the date of the date picker in the label and count down from that?

This is the full code:

var timer = NSTimer()
var counter = 5

@IBOutlet var countingLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!

@IBAction func start(sender: AnyObject) {
    // grab the selected date from the date picker
    let wakeUpTime = datePicker.date

    // count down
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
}

func updateCounter() {
    countingLabel.text = String(counter--)
}

Xcode "Undefined symbols for architecture i386" Error without any change on code, all of a sudden

I get the Undefined symbols for architecture i386. Here's what I did:

  1. I checked many times for miswriting .h .m extensions. They are true.

  2. I deleted Framework Search Paths and then wrote "./" being defined as "Recursive" as it was provided as a solution but it did not work also.

  3. Can it be related with Architecture settings, it is now set as $(ARCHS_STANDARD).

    Undefined symbols for architecture i386:
    "_OBJC_CLASS_$_EMDenemeSinaviCell", referenced from:
         __TFC8EduMobil24EMAssesmentEvaluationNEW9tableViewfS0_FTCSo11UITableView21cellForR        owAtIndexPathCSo11NSIndexPath_CSo15UITableViewCell in         EMAssesmentEvaluationNEW.o
    ld: symbol(s) not found for architecture i386
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    
    
  4. When i change the current Cell Class i am using to another Cell Class it does not give any error. But it gives the following warning:

    file was built for i386 which is not the architecture being linked (x86_64): 
    
    

How can I solve this error?

Weird iOS Keychain access group behaviour

Recently we added Apple Pay support to our project and it caused some problems accessing data stored in iOS KeyChain. Basically we couldn't access "old" data that was stored before adding the entitlements file. In the entitlement file we only got the com.apple.developer.in-app-payments value (we don't used shared keychain groups).

I manually dumped the keychain data from the simulator and noticed that the "old" data access group (agrp) is set to test and the new data (I wrote a value to the same "default" keystore to understand the difference) agrp is set to the bundle identifier.

Anyone knows what's the "test" agrp and why the old data gets that access group? More importantly - is there any way to access that old data again?

Authorized stay Parse SWIFT

My goal is: User, which login with his Username/Password, with Parse, must be stay authorized after app closing.

Core Data? Is there a way easier or simply?

Built a Universal Framework, still getting "file was built for arm64 which is not the architecture being linked (x86_64)"

I am trying to incorporate a framework into another project and run it on the iOS simulator. I created a universal framework using this technique: http://ift.tt/14pXkSP but I'm still getting

file was built for arm64 which is not the architecture being linked (x86_64)

What is wrong here?

How to disable Loggings of Apptentive in Xcode console?

Apptentive seems like a good addition to have. However it pollutes the Console with so many messages, that is unnecessary to see every time. It is distracting me from seeing important debug messages elsewhere.

Only an extract:

2015-05-10 10:15:45.134 xNews[34355:4228197] Loading ATSwizzle_NSObject_Bootstrap
2015-05-10 10:15:45.134 xNews[34355:4228197] Loading ATSwizzle_UIViewController_Bootstrap

According to the docs it's possible to disable them:

#import "ATConnect_Debugging.h"
[ATConnect sharedConnection].debuggingOptions = ATConnectDebuggingOptionsNone;

This doesn't work at all. I still get to see all those debug messages I don't care about. Any advice please?

How to disable button touch at the start in Swift

I have this button:

@IBAction func touch(sender: AnyObject) {
println("Hello, world!")
}

and another:

@IBAction func toggle(sender: AnyObject) {
//code to enable touch of button "touch"

I want to disable user touch of "touch" at the start of the app, and enable touch after tapping "toggle", how to realize it by code and in storyboard?

Getting location coordinates from Address

The user will be prompted enter his address in a textfield and in the backend I want to get the location coordinates of the address.

I’m using geocoding service from google but not any of their APIs. I read somewhere in their document that “use of the geocoder for any purpose other than obtaining locations that will be displayed using the google maps APIs is a violation of the Terms of Service”.

And this is how HTTP request I use

http://ift.tt/1DZVPVc

Can I do this? I’m confused because I'm not showing any map at all but I want to get the coordinates. Will this be violating their terms?

Responsive design Xcode 6 - How to set constraints to make your design resposive?

I got some seemingly easy problem.

Let's consider the following example:

enter image description here

These are 3 stripes, each 450 width and 150 height. I would like to make it resposive which basicly means that I want them to resize dependently on screen size. I tried three different sets of constraints, I list them below:

1)

a) set leading space and trailing space for each one

b) set top and bottom space for each one

2)

a) set leading space and trailing space for each one

b) set aspect ratio 3:1

set top and bottom spaces except the bottommost one (pinning it to the bottom leads to constraints conflict)

3)

a) set aspect raio 3:1

b) set top and bottom spaces for each one

I thought that the third option would work because once the vertical spaces are known, it should set the appropriate width to satisfy aspect ratio constraint. However, this didn't work, xcode decided to resize only only stripe without respect for aspect ratio.

Second option was close but still inappropriate. Without bottom space vertical position of whole set of stripes would vary for each screen size.

First option was totally wrong because without aspect ratio the stripes had various shapes.

Could you support me with either specific or general advice how to deal with such issues? WHat are the general rules for iOS responsive design. I guess fixing this simple, exemplary problem will tell me much about approach to resposive design.

EDIT: the thing I'd like to achieve is: fixed aspect ratio and fixed spaces between the stripes. Size, trailing & leading spaces, top and bottom spaces should vary on each screen, but should remain in the same ratio on each screen. Basicly, this should look nearly the same whatever the size of screen is.

Thanks in advance!

How to replace UISegmentedControl with THSegmentedControl

I have been using UISegmentControl objects on storyboard but it only supports selecting only a single segment,

enter image description here

so I found an alternative that is THSegmentedControl, Now the problem is that I can't replace UISegmentControl class in the identity inspector, it only shows UISegmentedControl:

enter image description here

So how can I use THSegmentedControl instead ?

How to use special character in NSURL?

My application is using an NSURL like this:

var url = NSURL(string: "http://ift.tt/1cldTmx")

When I tried to make a task for getting data from this NSURL like this:

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

        if error == nil {

            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("urlContent \(urlContent!)")
        } else {

            println("error mode")
        }

but I got error when trying to got data from that address, although when I using safari go to link: "http://ift.tt/1RqI2S6=Aïn+Béïda+Algeria&country=" I can see the data. How can I fix that?

iOS Distribution Certificate revoked itself in Xcode?

When i'm trying to resend my app to Apple using Xcode using a different build number, i found my iOS Distribution Certificate is revoked in Xcode. However, in the Keychain Access, it still shows my Distribution Certificate as valid. How do i fix this?

Release Command still working Xcode

hey guys i have old project and I can use still release command,However in my new projects i cannot use release command,I guess my new projects automatically release objects but in my old projecti have to use every object for release command to remove from memory,How can i upgrade my old project to avoid memory problem?

samedi 9 mai 2015

Find the time/date from min./hours/seconds swift 1.2 xcode 6.3

Sorry My Title Is So Bad. :(

I am making a app to find out how long it will be before you have to go collect your belongings from a game. So you enter how much ore you want and it will do the math, It will tell you how much wood you will need and how long it will be. I want to send them a local notification when the ore will be done cooking. SO i need a way to find what time it will be after the "unknown" amount of time for the ore to be done.

This is the code to find how long before the ore is done.

timeAmount = oreWanted * 11

enter image description here And after you start the timer I want it to find the date and time when it will be done, so it will notify the user. I tried just having a basic timer and when it reached 0 it did a local notification, but the app couldn't be closed because the timer would stop. I need a way so the app can be completely closed and still notify them. Thanks

Cells become unorganised after using Search Bar

I am using Search Bar and Search Display programmatically, the search and results are all working fine. The problem is with the cell hight when display the results, the cells shrink and become smaller as shown in the image; enter image description here

Her is the code I am using to control the cells hight:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

if (self.listArray.count >= 1) { //change 0 to whatever cell index you want taller
return 159;
}
else {
return self.listArray.count;
}

}

How can I control the cells hight after display the results?

Thanks

How to reverse engineer an Xcode project from an app?

Xcode deleted my project and everything is gone. The only thing that I have is the app in my iPhone 6. So is there any way that I can retrieve the Xcode project of the app?

How to Select multiple images and Video from camera roll objective c?

i try to select multiple images and multiple videos,image multiple selection is working properly and uploading properly ,am using ELCImagePickerController ,but when i click on video that also returns image file . So please help ma as soon as fast.so am posting that code also here

     - (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
     {
    [self dismissViewControllerAnimated:YES completion:nil];

for (UIView *v in [_scrollView subviews]) {
    [v removeFromSuperview];
}

CGRect workingFrame = _scrollView.frame;
workingFrame.origin.x = 0;

NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
for (NSDictionary *dict in info) {
    if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
        if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
            UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
            [images addObject:image];

            UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
            [imageview setContentMode:UIViewContentModeScaleAspectFit];
            imageview.frame = workingFrame;

            [_scrollView addSubview:imageview];

            workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
        } else {
            NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
        }
    } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
        if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
            UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];

            [images addObject:image];

            UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
            [imageview setContentMode:UIViewContentModeScaleAspectFit];
            imageview.frame = workingFrame;

            [_scrollView addSubview:imageview];

            workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
        } else {
            NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
        }
    } else {
        NSLog(@"Uknown asset type");
    }
}

self.chosenImages = images;

[_scrollView setPagingEnabled:YES];
[_scrollView setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];

}

Difference between push notification and nsnotifcation centre in iOS sdk

I have question about push notification and the Notification Center. I have built an app and now I want to support notification the the time hits 0 I'm doing like countdown app shows the release date for games and title. Should I use nsnotifcation center or push notification

How to get properties(title,description etc) of a NSURl without using UIWebView?

Is it possible to get the description, thumbnail and tittle of a NSURL link without UIWebView?

-[ViewController goto:]: unrecognized selector sent to instance

I created a segue from ViewController1 to ViewController2 and set its id to "getStarted".

I added the following code as a button click action to move to the second view controller by clicking that button:

- (IBAction)getStarted:(id)sender {
    [self performSegueWithIdentifier:@"getStarted" sender:nil];
}

But Xcode keeps giving the error:

-[ViewController goto:]: unrecognized selector sent to instance

What is going on here? I don't even have any goto method in my code! Btw, I chose "Present Modally" as the Segue type.

tableView printout to printer missing column headers

In my app I am using a button to print a tableview of information to a printer. I am using the simple code below to print. I get output fine and even in duplex mode. I use the exact output table for a variety of reports. My problem - How do I include a title and the column headers?

  • (IBAction)btnPrintTable:(id)sender {

    NSPrintOperation *op;

    op = [NSPrintOperation printOperationWithView:rptTable];

    if (op)

    [op runOperation];
    
    

    else{

    NSAlert *alert = [[NSAlert alloc] init];

    [alert addButtonWithTitle:@"Cancel"]; [alert setMessageText:@"No Table Data available for printing"]; [alert setInformativeText:@"Cancel and create table data"]; [alert setAlertStyle:NSWarningAlertStyle];

    if ([alert runModal] == NSAlertFirstButtonReturn){

    } } }

There are 6 column headers: Number: Extension: Year: Type: Price: Description:

I have read 'About MAC Printing' and 'Printing Programming Topics for Cocoa'. I can not reference a table header/column design detail. I can not find anything in pagination topics referencing this issue. Can anyone help?

Package cannot find info.plist

I am trying to submit my app to the app store. I have looked at a half a dozen questions similar to this one yet none have helped. Here is the error: Here is the error

Things I know. The file exist and had the correct path in the Build Settings.

Showing info.plist

It also exist in Finder.

enter image description here

Here is what is inside of the info.plist

Any idea what I am doing wrong? I cleaned and build cleaned the project. Even restarted my computer.

EDIT

Here is what the build log looks like when I search for .plist

enter image description here

The file is found in the project file

enter image description here

UIActivityTypePostToFacebook howto post image and text xcode ios NSDictionary key for text

in My CustomActivityItemProvider I got this code for custom Facebook share items:

@implementation CustomActivityItemProvider

@property(nonatomic,strong) NSString *text;
@property(nonatomic,strong) NSURL *url;
@property(nonatomic,strong) UIImage *image;

- (id)item {
            if ([self.activityType isEqualToString:UIActivityTypeMessage]) {
                return [NSString stringWithFormat:@"%@\n%@",self.text,self.url];
                }

            if ([self.activityType isEqualToString:UIActivityTypePostToFacebook]) {
                //>>>>FACEBOOK
                self.url = [NSUrl urlWithString:@"http://www.google.it"];
                self.text = @"FaceBookText";
                self.image = [UIImage imageNamed:@"imageShare.png"];
                NSDictionary *d = [[NSDictionary alloc] initWithObjects:@[self.text,self.image,self.url] forKeys:@[@"text",@"image",@"url"]];
                return d;
                }
        return @"";
    }

I can't send image and text... I have try with all possible key: "title" or "text" or "description" but nothing.. I see the img, I see the url.. but I don't see any text... can anyone explain what I'm doing wrong ??

thanks you !

I keep receiving invalid login parameters every time i try to log in a user on my Log in page

I am using swift with parse on xcode and i keep receiving this error:

[Error]: invalid login parameters (Code: 101, Version: 1.7.2)

whenever i try to log in a user i know the user is created in the parse backend and its information is correct. What can i do to stop this from happening and have the user log on without the application sending back invalid login parameters?

here is my LogInViewController:

import Foundation
import Parse
import UIKit
import Bolts

class LoginViewController: UIViewController, UITextFieldDelegate {


@IBOutlet weak var loginStatusLabel: UILabel!

@IBOutlet weak var emailTextField: UITextField!


@IBOutlet weak var passwordTextField: UITextField!


@IBOutlet weak var loginButton: UIButton!


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

    emailTextField.delegate = self
    passwordTextField.delegate = self
}

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

    login(emailTextField.text, password: passwordTextField.text)
}


func login(email: String, password: String)
{

    PFUser.logInWithUsernameInBackground("email", password: "password")
        {
        (user: PFUser?, error: NSError?) -> Void in
            if user != nil
            {
                user!.fetch()
                if user!.objectForKey("emailVerified") as! Bool
                {
                    self.loginStatusLabel.text = "Success!"
                }
                else if !(user!.objectForKey("emailVerified") as! Bool)
                {
                    self.loginStatusLabel.text = "Verify your email address!"
                }
                else // status is "missing"
                {
                    //TODO: Handle this error better
                    self.loginStatusLabel.text = "Verification status: Missing"
                }

            }
            else
            {
                if let errorField = error!.userInfo
                {
                    self.loginStatusLabel.text = (errorField["error"] as! NSString) as String
                }
                else
                {
                    // No userInfo dictionary present
                    // Help from http://ift.tt/1pXGMry
                }

            }
    }
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true;
}
}

where am i going wrong in logging in the user?

Apple Mach-O linker Error Xcode 6.2

I'm sorry if this question is a duplicate, but I only asked it because I didn't find a solution in other related questions.

I started a new project in Xcode 6.2 and I imported AFNetworking using pods. I also imported SWRevealViewController by dragging the two files (.h and .m) into the project.

Everything looks fine but when I build the project to test it gives me the error below.

Error Screenshot

Does anyone know how to deal with this?

Call Swift Callback in C [duplicate]

This question already has an answer here:

I have the following code in .c file:

void logger(void (*callback_func)())
{
    callback_func();
}

How do I call this function from swift code?

func callback()
{
    NSLog("Hello from Swift")
}

func main()
{
    logger(callback)
}

It works to call C function from Swift but I can't get it to work if it has a callback function as an argument.

How do I programmatically put constraint to buttons (horizontal spacing)

I would like to put side by side two buttons.

One ( testButton ) is currently at the right position - Vertically and Horizontally aligned - with Interface Builder Auto Layout.

Let's look :

Interface builder - auto layout - currently

I would like to put the other one ( okButton ) programmatically side by side :

Preview of what I want :

Interface builder - auto layout - result

I added a CenterY constraint and a Leading/Trailing one but it does not work, the UIButton width of the test button grow..

Let's take a look at the Debug View Hierarchy :

Interface builder - auto layout - Debug View Hierarchy

And my code :

override func viewDidLoad() {
        super.viewDidLoad()

        let constraintAlignY = NSLayoutConstraint(
            item: okButton,
            attribute: .CenterY,
            relatedBy: .Equal,
            toItem: testButton,
            attribute: .CenterY,
            multiplier: 1,
            constant: 0)

        let constraintXSpace = NSLayoutConstraint(
            item: okButton,
            attribute: .Leading,
            relatedBy: .Equal,
            toItem: testButton,
            attribute: .Trailing,
            multiplier: 1,
            constant: 8)

        view.addConstraint(constraintAlignY)
        view.addConstraint(constraintXSpace)
    }

Warning console :

2015-05-09 23:03:10.439 MainThreading[10227:663061] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7b8c8ee0 UIButton:0x7b8cde90'test'.centerY == UIView:0x7b8ced40.centerY>",
    "<NSIBPrototypingLayoutConstraint:0x7b8c40f0 'IB auto generated at build time for view with fixed frame' V:|-(191)-[UIButton:0x7b8ce8d0'ok']   (Names: '|':UIView:0x7b8ced40 )>",
    "<NSIBPrototypingLayoutConstraint:0x7b8c77f0 'IB auto generated at build time for view with fixed frame' V:[UIButton:0x7b8ce8d0'ok'(30)]>",
    "<NSLayoutConstraint:0x7b8c4f50 UIButton:0x7b8ce8d0'ok'.centerY == UIButton:0x7b8cde90'test'.centerY>",
    "<NSLayoutConstraint:0x7b8da380 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7b8ced40(480)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7b8c4f50 UIButton:0x7b8ce8d0'ok'.centerY == UIButton:0x7b8cde90'test'.centerY>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
(lldb) 

Any idea ? Thanks !

Keeping unused files in Xcode project

In Eclipse you can create a folder and name it, say, "unused", to keep currently unused files (incomplete code, resources for future use, etc) which are ignored by project builder. Can I have something similar with Xcode?

If I move a file to a project folder without inserting it with Xcode, it may be OK, and I will be able to see it while opening in Finder. However, it will be more convenient to have it listed by Project Navigator.

OpenCV for iOS framework error "Base.hpp" header must be compiled as C++

As the title says, I'm getting "XXX.hpp" header must be compiled as C++" whenever I try to #import an .hpp file.

Any tips for resolving this issue?

Ive tried numerous build settings configurations including setting a -lc++ linker flag.

Xcode won't open up ContentViewController but stays on the launch screen

I am trying to compile my Xcode application. It builds successfully however it doesn't get past the launch screen.

Also It keeps referring me to this particular line of code: instantiateViewControllerWithIdentifier (full code below) and in the logs I get this message:

"2015-05-09 21:36:20.376 banoffee[2104:430498] Unknown class ContentViewController in Interface Builder file. Could not cast value of type 'UIViewController' (0x10741f418) to 'HelloHi.ContentViewController' (0x1049aa2e0). (lldb) "

Can anyone please help me fix this?

import UIKit

class ViewController: UIViewController, UIPageViewControllerDataSource {

    var pageViewController: UIPageViewController!
    var pageTitles: NSArray!
    var pageImages: NSArray!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.pageTitles = NSArray(objects: "Welcome", "Hello")
        self.pageImages = NSArray(objects: "page1", "page2")

        self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController

        self.pageViewController.dataSource = self

        var startVC = self.viewControllerAtIndex(0) as ContentViewController
        var viewControllers = [startVC]

        self.pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: nil)

        self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60 )

        self.addChildViewController(self.pageViewController)
        self.view.addSubview(self.pageViewController.view)
        self.pageViewController.didMoveToParentViewController(self)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func restartAction(sender: AnyObject) {

        var startVC = self.viewControllerAtIndex(0) as ContentViewController
        var viewControllers = [startVC]

        self.pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: nil)

    }

    func viewControllerAtIndex(index: Int) -> ContentViewController

    {

        if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count))
        {
            return ContentViewController()
        }

        var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController

        vc.imageFile = self.pageImages[index] as! String
        vc.titleText = self.pageTitles[index] as! String
        vc.pageIndex = index

        return vc 


    }

    //MARK: - Page View Controller Data Source

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {

        var vc = viewController as! ContentViewController
        var index = vc.pageIndex as Int

        if (index == 0 || index == NSNotFound)
        {
            return nil
        }

        index--
        return self.viewControllerAtIndex(index)

    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {

        var vc = viewController as! ContentViewController
        var index = vc.pageIndex as Int

        if (index == NSNotFound)
        {
            return nil
        }

        index++
        if (index == self.pageTitles.count)
        {
            return nil
        }

        return self.viewControllerAtIndex(index)

    }

    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
        return self.pageTitles.count
    }

    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
        return 0
    }

}

constraints layout to textfields in a cell

Trying to find options to add constraints to the textfield that are in a table cell row. I'm trying to keep both of them 50% of the width and/either (pinned to the left right edges).

Not sure what constraints to add to achieve it in the Interface builder. Please advise.

storyboard screenshot

Programmatic access to the Photos Library on Mac OS X: PhotoKit / Photos Framework for Mac

In Objective-C, there's a Photos Framework a.k.a. PhotoKit which enables iOS developers to access the photos library on iPhone and iPad and to retrieve the pictures/videos along with their metadata.

How would Mac developers perform a similar task? It seems PhotoKit is only available in iOS 8.0. Is there an equivalent of the Photos Framework for Mac OS X?

xcodebuild clean failed - for a nonexistant scheme?

I'm currently configuring a Continuous Integration job for my workplace. I've run into some issues, that I hope you can help me with.

It starts like this.

[Info] Loading settings for scheme 'SPONTAN' ... (1764 ms)

=== CLEAN ===

xcodebuild clean SPONTAN
Pods / Pods-ActionSheetPicker-3.0 (Debug)
  ~ Check dependencies (9 ms)
  ~ Remove libPods-ActionSheetPicker-3.0.a (7 ms)
  ~ Remove Pods-ActionSheetPicker-3.0.build (5 ms)
  0 errored, 0 warning (13 ms)

Pods / Pods-ABPadLockScreen (Debug)
  0 errored, 0 warning (13 ms)

~ Check dependencies (10 ms)
~ Remove libPods-ABPadLockScreen.a (7 ms)
~ Remove Pods-ABPadLockScreen.build (5 ms)
Pods / Pods-Bolts (Debug)
  0 errored, 0 warning (12 ms)

...

SPONTAN / SPONTAN (Debug)
      ~ Check dependencies (80 ms)
      ~ Create product structure (0 ms)
--------------------------------------------------------------------------------
/bin/mkdir -p /b/d20150508-639-140oy5t/zios/ABVfrRTRd5bE2Fty/SPONTAN.app
--------------------------------------------------------------------------------
      ~ Remove SPONTAN.app (1 ms)
      ~ Remove SPONTAN-Prefix.pch.pch (1 ms)
      ~ Remove SPONTAN-Prefix.pch.pch (0 ms)
      ~ Remove SPONTAN.app.dSYM (0 ms)
      ~ Remove SPONTAN.build (0 ms)
      0 errored, 0 warning (83 ms)


  xcodebuild build clean
--------------------------------------------------------------------------------
Scheme Tests is not currently configured for the clean action.
--------------------------------------------------------------------------------


** CLEAN FAILED ** (2937 ms)

It says the clean of a scheme called Tests is not configured. Now I've been looking for a scheme called Tests for an hour without success. Is there any way to fix this? I've set all Schemes to have Shared enabled and autocreate schemes is disabled.

IOS openParentApplication is not waking up parent application

In my watchkit application I am using openParentApplication to communicate with the parent app however this is not always reliable especially if I have not used the parent app in some time. It seems that this is not waking up the parent app for communication. If I tap the parent app and launch it however, 2 way communication proceeds as normal and I get all my data. There are no crashes of any sort. The code is very sound.

Is this a known issue?

XCode simulator won't run most recent code

I've been writing an app and I've released one version to the app store. I've updated it slightly since then and have been playing with it on the simulator. Unfortunately the simulator has stopped reacting to my changes in code. I know it's the simulators fault because if I run the app on my ipad the changes take effect.

I've tried resetting the simulator by going iOS simulator -> reset content and settings I've tried quitting out of the simulator I've tried quitting out of xCode

I have no clue why the simulator is wrong. It's just blatantly not updating. I wish I could give more details but I really don't know much more.

Status bar's style issue

I need a "Light content" status bar for my iOS 8 app but it will show up as Dark. This thing persits and I can't get it work.

Some things I have tried

  • Setting the Status bar style in the Info.plist
  • Setting the style through code with UIApplication
  • Trying to set the UINavigationBar
  • Setting the Status bar property for UIViewControllers

None of the above works, I get a "Light content" on the Loading Screen storyboard but it gets dark as soon as it loads the starting UIViewController from the storyboard. Any thoughts why this is happening? Thank you.

iOS issue moving sprite kit node SpriteKit

Hello i'm tring to get the position of a sprite kit node. If it doesn't move is't all right i got the exact position in int's view.

But if a start a move action on it

[self runAction:[SKAction repeatActionForever:
                 [SKAction moveByX:-1
                                 y:0
                          duration:0.004]] withKey:@"movingWave"];

the following code display the origin position of the sprit kit node and not the position that the object have related to the view

    SKNode *tmp = [self childNodeWithName:[NSString stringWithFormat:@"waves%d", numwaves]];
    CGPoint pos=[super convertPointFromView:tmp.position];
    NSLog(@"%f",pos.x);

/*terminal */

2015-05-09 20:34:58.620 Wave's attack[2349:607] -284.000000

2015-05-09 20:34:58.652 Wave's attack[2349:607] -284.000000

Why can't my project code access my cocoapods?

I'm using cocoapods to add SnapKit to my iOS project. However, none of the functions from SnapKit are accessible from my source code. Xcode immediately throws a compiler warning along this lines of "this doesn't exist"

I followed the install instructions listed here. I also have the xcworkspace open that cocoapods created and I see my app project and a Pods project. I did notice that under Pods/Product in the navigator I see "Pods.framework" and "SnapKit.framework" in red. When I run find . | grep SnapKit.framework in my project directory, nothing turns up.

After digging around I believe SnapKit.framework is in my DerviedData folder under ~/Library/Developer/XCode . I did notice that under the build settings for Pods PODS_FRAMEWORK_BUILDPATH is set to look in a builds directory under my project, which does not exist. Perhaps that's the issue? Are my pods supposed to build in a build directory? How would I make them do that?

Auto login in webview OS X

I am new in OS X development. I try to auto-connect my app to a website. I have try an ios code but it's don't work.

My code :

Appdelegate.m

 NSString *urlAddress = @"http://ift.tt/1DYDZ4T";

NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];


[webview setCustomUserAgent: @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.74.9 (KHTML, like Gecko) Version/7.0.2 Safari/537.74.9"];

[[webview mainFrame] loadRequest:requestObj];

In my ios app, to login to my website I use this :

NSString *urlString = @"http://ift.tt/1eeEnPI";


//NSURL *url = [NSURL URLWithString:urlString];
NSURL *url = [NSURL URLWithString:urlString];


//NSURLRequest *request = [NSURLRequest requestWithURL:url];

//Add some informations POST
NSString *post = [NSString stringWithFormat:@"id=%@&password=%@&user=%@", server_id, server_password, user];;


NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];


NSOperationQueue *queue = [[NSOperationQueue alloc] init];


[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil) [_seedbox loadRequest:request];
     else if (error != nil) NSLog(@"Error: %@", error);
 }];

But this code isn't work. Thanks for your help.

navigationItem titleview align center between buttons

I have the code likes, in the title bar I am having 3 buttons, left search button, right camera button and option button, in between I am having title.

What I want to do is, I want to display the title centered between the search button and Camera button, can anyone help me how to do this.

//Left Button
UIBarButtonItem *leftSearch = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_search"] style:UIBarButtonItemStyleBordered target:self action:@selector(gotoSearch)];

leftSearch.imageInsets = UIEdgeInsetsMake(0, -5.0f, 0, 0);

[leftSearch setTintColor:[UIColor whiteColor]];
/////////

//Right Button -- First Camera
UIBarButtonItem *rightCamera = [[UIBarButtonItem alloc]
                                initWithImage:[UIImage imageNamed:@"icon_camera"]
                                style:UIBarButtonItemStyleBordered
                                target:self
                                action:@selector(gotoPhotoGallery)];
[rightCamera setTintColor:[UIColor whiteColor]];
rightCamera.imageInsets = UIEdgeInsetsMake(0, 0, 0, -59.0f);
///////////////////

//Right second Button -- for options menu
UIBarButtonItem *rightMenu = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header_option"] style:UIBarButtonItemStyleBordered target:self action:@selector(gotoPhotoGallery)];
[rightMenu setTintColor:[UIColor whiteColor]];
rightMenu.imageInsets = UIEdgeInsetsMake(0, 0, 0, 5.0f);
///////////////////

NSArray *buttons = @[rightMenu, rightCamera];

self.navigationItem.rightBarButtonItems = buttons;

[[self navigationItem] setLeftBarButtonItem:leftSearch];

//Title Label

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Museo Sans" size:20];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = LoginUserName;
self.navigationItem.titleView = label;
[label sizeToFit];

Trying to implement iAd removal but getting "AnyObject is not convertible to..."

I am very new to swift, and I'm getting 5 error messages telling me that AnyObject isn't convertible to various the following: NSString; SKProduct; Set; and SKPaymentTransaction. What does this mean and how do I fix this?

Thanks in advance.

import UIKit
import StoreKit
import AVFoundation
import iAd



class ViewController: UIViewController,SKPaymentTransactionObserver, SKProductsRequestDelegate, ADBannerViewDelegate {

@IBOutlet var adBanner: ADBannerView!

var product: SKProduct!


override func viewDidLoad() {
    super.viewDidLoad()
    self.adBanner.hidden = true
    self.adBanner.delegate = self
    removeAdsButton.hidden = true

    if NSUserDefaults.standardUserDefaults().objectForKey("Ads")  == nil {
        SKPaymentQueue.defaultQueue().addTransactionObserver(self)
        self.getProductInfo();
    }
    if var status: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("Ads"){
        if status as NSString == "purchased" {
            self.adBanner.removeFromSuperview()
            self.removeAdsButton.hidden = true;
            self.removeAdsButton.userInteractionEnabled = false
        }
        else{
            SKPaymentQueue.defaultQueue().addTransactionObserver(self)
            self.getProductInfo()
        }
    }


    audioPlayer = AVAudioPlayer(contentsOfURL: evilMusic, error: nil)
    audioPlayer.prepareToPlay()


}

// Hide status bar
override func prefersStatusBarHidden() -> Bool {
    return true
}

@IBOutlet weak var janitor: UIImageView!
@IBOutlet weak var removeAdsButton: UIButton!


var evilMusic = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a")!)
var audioPlayer = AVAudioPlayer()


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
    NSLog("%@",error)
}

func bannerViewDidLoadAd(banner: ADBannerView!) {
    self.adBanner.hidden = false
}

func bannerViewWillLoadAd(banner: ADBannerView!) {

}

func bannerViewActionDidFinish(banner: ADBannerView!) {

}

func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
    let products = response.products
    if (products.count != 0)
    {
        product = products[0] as SKProduct
    }
    removeAdsButton.hidden = false
}

func getProductInfo(){
    if (SKPaymentQueue.canMakePayments()){
        let productID:NSSet = NSSet(object: "com.evileye.removeads")
        let request:SKProductsRequest = SKProductsRequest(productIdentifiers: productID)
        request.delegate = self
        request.start()
    }
}

func storePurchase(){
    NSUserDefaults.standardUserDefaults().setObject("purchased", forKey:"Ads")
    NSUserDefaults.standardUserDefaults().synchronize()
    self.adBanner.removeFromSuperview()
    self.removeAdsButton.hidden = true
    self.removeAdsButton.enabled = false

}

func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!){
    for transaction:AnyObject in transactions {
        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
            switch trans.transactionState {
            case .Purchased:
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                self.storePurchase()

                break;
            case .Failed:
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                break;
            case .Restored:
                SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
                break;
            default:
                break;
            }
        }
    }
}



@IBAction func removeAdsTapped(sender: AnyObject) {
    let payment:SKPayment = SKPayment(product: product);
    SKPaymentQueue.defaultQueue().addPayment(payment);

}

Xcode Counter/ Countdown

Hello guys iam very new in programming. But I want to programm an app with a Start-Button which Starts a Countdown and an extra Counter. The Counter should count the taps at an extra Label-Field. The Countdown should go down from 10 seconds to 0 and then stops the Game so that you cant tap anymore, before restarting. So it would be nice to get an Code from you! Thank you very much for answering! And sorry for the Bad Englisch, iam an German 9th grader.

So I'm making an app on Xcode and the build fails even though there are no errors in the code. I do, however, get this error: Compiler error Dictionary <>key, value <> is not convertible to hashable. How can I fix this? I have searched this but found nothing helpful.

Thanks so much in advance!

I am trying to build my Xcode project however, I keep getting "Could not find member " build errors in three different instances from the code below. Please help.

Instances:

  1. Could not find member 'dataSource'

2&3. Could not find member 'Forward'

import UIKit

class ViewController: UIViewController, UIPageViewControllerDataSource {
    
    var pageViewController: UIViewController!
    var pageTitles: NSArray!
    var pageImages: NSArray!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.pageTitles = NSArray(objects: "Welcome", "Hello")
        self.pageImages = NSArray(objects: "page1", "page2")
        
        self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
        
        self.pageViewController.dataSource = self
        
        var startVC = self.viewControllerAtIndex(0) as ContentViewController
        var viewControllers = NSArray(object: startVC)
        
        self.pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: nil)
        
        self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60 )
        
        self.addChildViewController(self.pageViewController)
        self.view.addSubview(self.pageViewController.view)
        self.pageViewController.didMoveToParentViewController(self)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func restartAction(sender: AnyObject) {
        
        var startVC = self.viewControllerAtIndex(0) as ContentViewController
        var viewControllers = NSArray(object: startVC)
        
        self.pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: nil)
        
    }

    func viewControllerAtIndex(index: Int) -> ContentViewController
        
    {
        
        if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count))
        {
            return ContentViewController()
        }
        
        var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
        
        vc.imageFile = self.pageImages[index] as! String
        vc.titleText = self.pageTitles[index] as! String
        vc.pageIndex = index
        
        return vc 
        
        
    }
    
    //MARK: - Page View Controller Data Source
    
    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
        
        var vc = viewController as! ContentViewController
        var index = vc.pageIndex as Int
        
        if (index == 0 || index == NSNotFound)
        {
            return nil
        }
        
        index--
        return self.viewControllerAtIndex(index)
        
    }
    
    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        
        var vc = viewController as! ContentViewController
        var index = vc.pageIndex as Int
        
        if (index == NSNotFound)
        {
            return nil
        }
        
        index++
        if (index == self.pageTitles.count)
        {
            return nil
        }
        
        return self.viewControllerAtIndex(index)
        
    }
    
    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
        return self.pageTitles.count
    }
    
    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
        return 0
    }
    
}

I cannot use viewDidAppear and viewDidDisappear at the same project

radarMap is a UIWebView object and exitMapButton is its close button. To access map I used hidden actions. Now I want to add fade out and fade in animations while hiding. I did fade in but not fade out. How can I add fade out animation while hiding?

func openRadarMap(){
        radarMap.hidden = false
        exitMapButton.hidden = false
        self.radarMap.alpha = 0
        self.exitMapButton.alpha = 0

    }

    override func viewDidAppear(animated: Bool) {

        if radarMap.hidden == false {
        super.viewDidAppear(animated)
        UIView.animateWithDuration(0.5, animations: {
            self.radarMap.alpha = 1.0
            self.exitMapButton.alpha = 1.0
        }) }
    }

    func exitFromMap() {
        exitMapButton.hidden = true
        radarMap.hidden = true
        self.exitMapButton.alpha = 0.0
        self.radarMap.alpha = 0.0
    }



    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        UIView.animateWithDuration(0.5, animations: {
            self.radarMap.alpha = 0.0
            self.exitMapButton.alpha = 0.0
        })
    }

    @IBAction func exitMapButtonAction(sender: AnyObject) {
        exitFromMap()
    }



    @IBAction func webView(sender: UIButton) {
        getAd()
       openRadarMap()
        let URL = "http://ift.tt/1P8sF1U"
        let requestURL = NSURL(string:URL)
        let request = NSURLRequest(URL: requestURL!)
        radarMap.loadRequest(request)
        //performSegueWithIdentifier("mapView", sender: nil)
    }

unable to change variable values in Xcode playground

I am just starting out in Xcode6 and using Playground to test out some Swift commands. I test a simple var a = 10, var b = 15 and var total = a+b So far so good. But when I change value of a from 10 to 20, it doesn't seem to be updated. The calc. still reflects 10+15 vs. 20+15. This sounds silly but how come variable values aren't updated? Should I be using different variables or doing something else? I would have expected the 'right panel' to update instantly with my changes. Thanks!

Unexpected categoryBitMask value with SpriteKit and Swift

I am trying to detect contact between two nodes in SpriteKit with Swift, but when contact was made, I got unexpected value for the categoryBitMask. With the following block of code, I should expected to get the value of 1 or 2 for bodyA, 3 or 4 for bodyB, instead of that, I got the value 1 or 2 for bodyA, but I got a value of 4294967295 for bodyB. Any ideas why this happened? and how I can fix it? Thanks.

func testAddingSprites() {

    var fallSprite = SKSpriteNode()
    let fallingShapeIndex = Int(arc4random_uniform(UInt32(fallingShape.count)))
    switch fallingShapeIndex {
    case 0:
        fallSprite = SKSpriteNode(imageNamed: "rectangle.png")
        fallObj.append(fallSprite)
        println(fallObj.count, fallingShapeIndex)
        fallSprite.physicsBody?.categoryBitMask = 3
        fallSprite.physicsBody?.contactTestBitMask = 1 | 2
    case 1:
        fallSprite = SKSpriteNode(imageNamed: "circle.png")
        fallObj.append(fallSprite)
        println(fallObj.count,fallingShapeIndex)
        fallSprite.physicsBody?.categoryBitMask = 4
        fallSprite.physicsBody?.contactTestBitMask = 1 | 2
    default:
        println("Unexpected fallingShapeIndex", fallingShapeIndex)
    }

    fallSprite.physicsBody = SKPhysicsBody(circleOfRadius: 50)
    fallSprite.position = CGPointMake(self.frame.width / 2, self.frame.height / 2 + 250)
    fallSprite.physicsBody?.dynamic = true
    fallSprite.physicsBody?.affectedByGravity = false

    self.addChild(fallSprite)

    // set fall object movment
    let moveAction = SKAction.moveTo(CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - 110), duration: 3)
    let cleanAction = SKAction.removeFromParent()
    fallSprite.runAction(SKAction.sequence([moveAction, cleanAction]), withKey: "fallObjMove")

}

Here are some solutions I already tried,

  1. I tried to assign the categoryBitsMask by the following code, I got the same unexpected value.

    enum fallObjGroup:UInt32 {
        case rectangleFall = 1
        case circleFall = 2
    }
    enum matchObjGroup:UInt32 {
        case rectangleMatch = 1
        case circleMatch = 2
    }
    
    
  2. I tried to clean build folder, and restart Xcode, no luck either.

EDIT: code for getting the value:

func didBeginContact(contact: SKPhysicsContact) {
    if contact.bodyA.categoryBitMask == 1 && contact.bodyB.categoryBitMask == 3 {

        println("rectangle contact made", Int(contact.bodyA.categoryBitMask),Int(contact.bodyB.categoryBitMask))

    } else if contact.bodyA.categoryBitMask == 2 && contact.bodyB.categoryBitMask == 4 {

        println("circle contact made", Int(contact.bodyA.categoryBitMask),Int(contact.bodyB.categoryBitMask))

    } else {

        println("GAME OVER!!!", Int(contact.bodyA.categoryBitMask),Int(contact.bodyB.categoryBitMask))

    }
}

Result: (GAME OVER!!!, 1, 4294967295) & (GAME OVER!!!, 2, 4294967295)

Put request IOS

I try to update a object in the database trough a API call. I do this action with a PUT request. A Post request was already made and is working fine. I thought it is just copy paste...

The API part works fine because if I execute the following curl command than it updates the row I wanted in the database

$ curl -H 'Accept: application/json' -i -X PUT -d 'UserLogin=Ub0D&EndDate=2014-01-17 00:00:00.0000000&Sport=Fietsen&Distance=1000&Duration=10&Achieved=true&DateCreated=2015-05-09 12:01:00.000000' http://localhost:8089/api/goal/ub0d -k -u ub0d:test123

But now the part in swift gives me a bad request error (400)... This is my code

    var url : NSURL
    url = NSURL(string: _apiUrl + connectToApi(apiCall) + String("\(AccountRepository.Instance.getCurrentUserName())"))!

    let request = NSMutableURLRequest(URL: url)

    if postString != nil {

        let postData : NSData = ("UserLogin=Ub0D&EndDate=2014-01-1700:00:00.0000000&Sport=Fietsen&Distance=1000&Duration=10&Achieved=true&DateCreated=2014-01-1700:00:00.0000000").dataUsingEncoding(NSUTF8StringEncoding)!
        // create the request
        request.HTTPMethod = "PUT"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
        request.setValue("application/json", forHTTPHeaderField: "Content-type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.HTTPBody = postData
    }
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!

I'm really stuck on it:(

RestKit RKObjectMapping Swift Optional

I have a swift model called Activity that can optionally have a coordinate attached to it.

import MapKit

class Activity: NSObject {

    var coordinate: CLLocationCoordinate2D?

    class func objectMapping() -> RKObjectMapping {
        let mapping = RKObjectMapping(forClass: self)

        let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate")
        coordinateMapping.valueTransformer = RKCLLocationCoordinate2DValueTransformer()
        mapping.addPropertyMapping(coordinateMapping)

        return mapping
    }
}

When launching my application this however gives me:

2015-05-05 12:14:30.741 Sample[54338:531558] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key coordinate.'

If I change coordinate to be non-optional and supply a default the application runs.

So my question is how do I use RestKit in swift in regards to Optionals?

Xcode 3.6.1 Login Tutorial : JSON no response

I learning IOS and i try to build login app with Xcode 6.3.1, Swift, JSON & PHP. my code :

            var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

        if ( urlData != nil ) {
            let res = response as! NSHTTPURLResponse;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData);

                var error: NSError?

                var jsonData: NSDictionary?
                if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary {

                    let success:NSInteger = jsonData.valueForKey("success") as! NSInteger

                    //[jsonData[@"success"] integerValue];

                    NSLog("Success: %ld", success);

                    if(success == 1)
                    {
                        NSLog("Login SUCCESS");

                        var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
                        prefs.setObject(username, forKey: "USERNAME")
                        prefs.setInteger(1, forKey: "ISLOGGEDIN")
                        prefs.synchronize()

                        self.dismissViewControllerAnimated(true, completion: nil)
                    } else {
                        var error_msg:NSString

                        if jsonData["error_message"] as? NSString != nil {
                            error_msg = jsonData["error_message"] as! NSString
                        } else {
                            error_msg = "Unknown Error"
                        }
                        var alertView:UIAlertView = UIAlertView()
                        alertView.title = "Sign in Failed!"
                        alertView.message = error_msg as String
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()

                    }

                }

            } else {
                var alertView:UIAlertView = UIAlertView()
                alertView.title = "Sign in Failed!"
                alertView.message = "Connection Failed"
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }
        } else {
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Connection Failure"
            if let error = reponseError {
                alertView.message = (error.localizedDescription)
            }
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        }
    }

But when i run the app with correct Username & password. This block always skipped(false)

var jsonData: NSDictionary?
                if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary {

and this is my PHP code response if username & password match

error_log("User $email: password match.");
        echo '{"success":1}';

please help

Can't use imshow in xcode 5 on OSX 10.8

I'm kind of puzzled as I cannot use imshow from the opencv library. I use plenty of other function from opencv, but I get this error, when I want to show my matrix/image.

Undefined symbols for architecture x86_64:
  "cv::namedWindow(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)", referenced from:
      _main in main.o
  "cv::imshow(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, cv::_InputArray const&)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The the codelines/functions throwing this error are:

cvStartWindowThread();
namedWindow("DisplayImage", WINDOW_AUTOSIZE);
imshow("Display Image", img_bgr);

where img_bgr is my desired matrix.

I'm working on OSX 10.8.5 with Xcode 5.1.1 and opencv-2.4.10 was installed via this walkthrough.

Anyone has an idea and can help why I can't call those above functions? I searched for threads concerning this problem, but none seemed to be satisfying.

EDIT:

Have uninstalled and installed OpenCV twice now. Once with Cmake itself (as application) and once with help of this tutorial. Nothing worked out still get the same error. Does no one have an idea?

How to move to another view controller in iOS on a Button Click

Let's say I created two view controllers on storyboard - FirstViewcontroller and SecondViewcontroller. Now I wanna move to SecondViewcontroller by clicking a button in FirstViewcontroller. What should I do to the button? I have ctrl clicked the button and connected it to the SecondViewcontroller using "reveal view controller push controller". Is there anything else to do in the code?

Application works fine in development but having a crash on opening an AdHoc build

I have swift project and have used objective c frameworks installed via cocoa pods . The application is for iOS 8 and above devices .

Application works fine in development but having a crash on opening an AdHoc build .

enter image description here

Xcode Swift: extension of array: "can't invoke.. with argument list .. "

Motivation: Trying to construct an 'contains' function that return true or false depending on if the array contains the parameter supplied in object.

Error: Can't invoke 'exist' with argument list of type '((T) -> Bool)'

I can't tell if the problem is in extension of Array,or in the closures. Both expressions in contains() have similar error.

The error looks ridiculous since ((T) -> Bool) is exactly what I have written for parameter of 'exist'

extension Array{    
    func exist(requirement:(T) -> Bool) -> Bool{
        for a in self{
            if(requirement(a)){
                return true
            }
        }
        return false
    }
    func contains(a:T) -> Bool{
        //return exist{return $0==a}
        return exist{(s0:T)->Bool in return s0==a}
    }
}

Use of undeclared identifier '$eax'

i'm getting this error in Xcode 6.2 whenever i run my code using my iPhone. The code runs fine in the simulator. What could be the cause?

The breakpoint is in AppDelegate.swift:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate

Swift : AVPlayer don't work

I'm a trying sample and don't work. I just add my url and paste the code. I'm not getting error. Simulator is working, but i see empty page.

Code :

var f=CGRectMake(0, 0, 500, 500)
var url=NSURL(string: "https://www.youtube.com/watch?v=YqeW9_5kURI&spfreload=10")
var playerItem = AVPlayerItem(URL: url)

var v = UIView(frame:f)
var player=AVPlayer(playerItem: playerItem)
var playerLayer=AVPlayerLayer(player: player)

playerLayer.frame=f
v.layer.addSublayer(playerLayer)
player.play()

I'm using viewcontroller. I saw avkit player viewcontroller in object library. Should i use that viewcontroller ? What can i do ?

swift error self. used before super.init() call

Can anyone tell me please what i am doing wrong, i also tried to use the super.init before initializing the objects and tried self. infront of my objects

Thanks in advance!

the code i currently have is :

    //
//  RecordController.swift
//  TuneUpV2
//
//  Created by Don Nijssen on 05-05-15.
//  Copyright (c) 2015 Don Nijssen. All rights reserved.
//

import UIKit
import AVFoundation

class RecordController: NSObject {

    var audioEngine: AVAudioEngine
    var audioInputNode : AVAudioInputNode
    var audioPlayerNode: AVAudioPlayerNode
    var audioMixerNode: AVAudioMixerNode
    var audioBuffer: AVAudioPCMBuffer

    override init(){

        audioEngine = AVAudioEngine()
        audioPlayerNode = AVAudioPlayerNode()
        audioInputNode = AVAudioInputNode()
        audioMixerNode = AVAudioMixerNode()
        audioBuffer = AVAudioPCMBuffer()


        audioMixerNode = audioEngine.mainMixerNode

        let frameLength = UInt32(256)
        audioBuffer = AVAudioPCMBuffer(PCMFormat: audioPlayerNode.outputFormatForBus(0), frameCapacity: frameLength)
        audioBuffer.frameLength = frameLength

        audioInputNode = audioEngine.inputNode

        audioInputNode.installTapOnBus(0, bufferSize:frameLength, format: audioInputNode.outputFormatForBus(0), block: {(buffer, time) in
            //let channels = UnsafeArray(start: buffer.floatChannelData, length: Int(buffer.format.channelCount))
            //let floats = UnsafeArray(start: channels[0], length: Int(buffer.frameLength))

            for var i = 0; i < Int(self.audioBuffer.frameLength); i+=Int(self.audioMixerNode.outputFormatForBus(0).channelCount)
            {
                // doing my real time stuff
                //self.audioBuffer.floatChannelData.memory[i] = floats[i];
                println(self.audioEngine.inputNode.rate);
            }
        })

        // setup audio engine
        audioEngine.attachNode(audioPlayerNode)
        audioEngine.connect(audioPlayerNode, to: audioMixerNode, format: audioPlayerNode.outputFormatForBus(0))

    }


    func start()
    {

        audioEngine.startAndReturnError(nil)

        // play player and buffer
        audioPlayerNode.play()
        audioPlayerNode.scheduleBuffer(audioBuffer, atTime: nil, options: .Loops, completionHandler: nil)
    }

    func stop()
    {
        audioEngine.stop();
        audioPlayerNode.stop();
    }

}