lundi 29 juin 2015

Does appcelerator studio work without internet connection once its installed?


My system specifications are : 

 Operating System Name         = Mac OS X

      Version                     = 10.10

      Architecture                = 64bit

      # CPUs                      = 4

      Memory                      = 4294967296

    Node.js

      Node.js Version             = 0.12.4

      npm Version                 = 2.10.1

    Titanium CLI

      CLI Version                 = 4.0.1

    Titanium SDK

      SDK Version                 = 4.0.0.GA

      SDK Path                    = /Users/systemname/Library/Application Support/Titanium/mobilesdk/osx/4.0.0.GA

      Target Platform             = iphone

The problem that i am facing is that i need continous internet connection for launching the app on device.Is there some setting which i can make to run without internet connection?

Thanks in advance.


Check if value is in sqlite database before adding


I am trying to preload some values into a database from a .csv file, but if they already exist then skip them. I am able to successfully parse the csv file then have the following function to check if they exist in the database:

func GetPreloadedDriverExists(manufacturer: String, model: String, size: Float, impedance: Int) -> Bool
{
    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let fetchRequest = NSFetchRequest(entityName:"Drivers")
    fetchRequest.propertiesToFetch = ["size"]
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format: "(manufacturer MATCHES %@) AND (model MATCHES %@) AND (#size == %@) AND (impedance == %@) AND (isRemovable == FALSE)", "\(manufacturer)", "\(model)", "\(size)", "\(impedance)")

    //3
    var error: NSError?

    let fetchedResults:NSArray = (managedContext.executeFetchRequest(fetchRequest, error: &error))!

    return fetchedResults.count == 0 ? false : true
}

The first time through this return false as I would expect for all entries, but when I open the sqlite file on the device, it is blank. If I remove the condition to check if they already exist, the database populates correctly.

Here is the loop I am using to add the entries into the database.

if let managedObjectContext = self.managedObjectContext {
     for item in items {
     // Check if driver already exists in database, if not add it.
          if(!GetPreloadedDriverExists(item.manufacturer, model: item.model, size: (item.size as NSString).floatValue, impedance: (item.impedance as NSString).integerValue))
          {
               println("Value does not exist")
               let menuItem = NSEntityDescription.insertNewObjectForEntityForName("Drivers", inManagedObjectContext: managedObjectContext) as! Drivers
                        menuItem.manufacturer = item.manufacturer
                        menuItem.model = item.model
                        menuItem.size = (item.size as NSString).floatValue
                        menuItem.impedance = (item.impedance as NSString).integerValue

                if managedObjectContext.save(&error) != true {
                     println("insert error: \(error!.localizedDescription)")
                }
           }
      }
 }

Thank you for the help and any feedback.


Making a web proxy for ipads by using a iframe


To keep this short, I'd like to make a website that, using a iframe connects to my server and from their to any website the user wants this would allow ipads to connect to my site and through a proxy to access google, facebook, ect. Let me know if any more explanation is necessary P.S. - I cant use the built in vpn on ipads due to restrictions.


Unknown attribute 'objc_boxable' ignored?


I'm trying to typedef a struct and box it into a dictionary value. I tried this code from the clang website, but no dice:

typedef struct __attribute__((objc_boxable)) _SizeA {
    CGFloat height;
    CGFloat width;
} SizeA;

The typedef is warned `Unknown attribute 'objc_boxable' ignored.

Xcode 6.3 with iOS SDK 8.3 targeting 8.0. Is there a trick here I'm missing?


iOS: User inactivity/idle


I want to find the user in activity and do some operation if the user inactive for some times. I have used the below link to implement the inactivity: stack overflow question But issue is that the TIMERUIApplication is not invoked all times. When I killed the app and reopen it the TIMERUIApplication is not called and the notification is not fired. Does anyone have any idea about this. Thanks in advance.


Share Facebook permissions between Android and iOS


I'm developing an App for Android and iOS. One of the permissions I ask from Facebook is for the user friends, but since you can only get the friends that also gave permissions to your App and since I had to register an App of iOS and one of Android in Facebook from iOS I can only get the users that are using my App on iOS.

How can I get all the friends that gave permission of my App regardless of the platform?


UIAlertView for when fetching JSON fails


I'm trying to get this UIAlertView to run when fetching the JSON data fails, but i can't seem to get it to work. I'd appreciate it if someone could show me how to do it or point me in the right direction!


Email PDF file on iOS


I'm writing a function to send a pdf file via email. On iOS I am encountering an issue where a pdf file gets generated and attached to an email and sent successfully, but the received email does not contain the original pdf file for some reason.

Here is my implementation using MFMailComposeViewController.

MFMailComposeViewController *mailer = [[[MFMailComposeViewController alloc] init] autorelease];
[mailer setMailComposeDelegate: id(m_delegate)];
[mailer setSubject:subject.toNSString()];
NSMutableArray *toRecipients = [[NSMutableArray alloc] init];
for(int i = 0; i < recipients.length(); i++)
{
    [toRecipients addObject:recipients.at(i).toNSString()];
}
[mailer setToRecipients:toRecipients];
NSString *emailBody = body.toNSString();
[mailer setMessageBody:emailBody isHTML:NO];


// Determine the file name and extension
attachedFile = "/var/mobile/Containers/Data/Application/1DFBF012-4838-4350-B465-ECF247831EB3/Library/Application Support/test.pdf";
NSArray *filepart = [attachedFile.toNSString() componentsSeparatedByString:@"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];

// Get the resource path and read the file using NSData
NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];

// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:@"jpg"]) {
    mimeType = @"image/jpeg";
} else if ([extension isEqualToString:@"png"]) {
    mimeType = @"image/png";
} else if ([extension isEqualToString:@"doc"]) {
    mimeType = @"application/msword";
} else if ([extension isEqualToString:@"ppt"]) {
    mimeType = @"application/vnd.ms-powerpoint";
} else if ([extension isEqualToString:@"html"]) {
    mimeType = @"text/html";
} else if ([extension isEqualToString:@"pdf"]) {
    mimeType = @"application/pdf";
}

// Add attachment
[mailer addAttachmentData:fileData mimeType:mimeType fileName:filename];


[qtController presentViewController:mailer animated:YES completion:nil];

I was able to see the file got attached to an email and sent it. I was able to receive the email sent. However, when I opened up the email it did not contain the file attached.

Any suggestion how I can troubleshoot this issue?

Here is my implementation of saving PDF file which follows standard file system path for saving application data.

/* Generate PDF file for sharing */
CGRect pageRect = CGRectMake(0, 0, 640, 480);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString * newFilePath = [documentPath stringByAppendingPathComponent:@"test.pdf"];
NSString *strFilename = newFilePath;
MyCreatePDFFile(pageRect, [strFilename UTF8String]);

I'm looking if there is a way to get the PDF file generated for trouble-shooting. It's located in Application Support directory which other application has no access to due to sand box policy. How do I get to access the PDF file?


Notification Issues in Xcode 6.3.2 With Swift


I'm using Swift in Xcode 6.3.2, and I'm trying to develop an app that sends local notifications. How do I get user permission to display notifications?


Programaticaly Click 10 UIButtons one after another in UIScrollView


I am developing one control where 10 UIButtons are added in UIScrollView. Now i have a requirement to click every Button one after another after some delay. can you all guide me how to do that?

here is the code what i have done.

in viewcontroller.h file

@property (weak) IBOutlet UIScrollView *mapScrollView;
@property (strong) UIButton *addContactIcon;

in viewcontroller.m file

// Set up ScrollView with UIButtons
NSUInteger xPosition = 1;
NSUInteger countIndex = 0;
for (ContactModule *sortedContacts in _distanceList) {

    _addContactIcon = [[UIButton alloc] initWithFrame:CGRectMake(xPosition, 7, 30, 30)];
    _addContactIcon.tag = countIndex;
    [_addContactIcon addTarget:self action:@selector(mapsScrollButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    _addContactIcon.layer.cornerRadius = 2.0;
    _addContactIcon.clipsToBounds = YES;
    [_addContactIcon setBackgroundImage:[UIImage imageWithContentsOfFile:dataPath] forState:UIControlStateNormal];
    [_addContactIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_mapScrollView addSubview:_addContactIcon];
    xPosition += _addContactIcon.frame.size.width + 2;
    countIndex = countIndex + 1;
}
_mapScrollView.contentSize = CGSizeMake(30 * _distanceList.count + 34, 40);
[_mapScrollView setShowsHorizontalScrollIndicator:NO];

Here is the Button Click Method For Every Button:

- (void)mapsScrollButtonClicked:(UIButton *)clickButton {

    // Set Annotation Callout
    [_mapsView selectAnnotation:[_mapsView.annotations objectAtIndex:clickButton.tag] animated:YES];
}

Now the requirement is I want to call Action Method for Every UIButtons in UIScrollview. for that i am doing something wrong below. help me with that:

for(NSUInteger count=0; count<[_distanceList count];count++)    {

            [UIView animateWithDuration:0.4
                              delay:0.8
                            options:0
                         animations:^{
                             [_addContactIcon sendActionsForControlEvents:UIControlEventTouchUpInside];
                         } completion:nil];
 }


how to give Page View Controller a "Cover Vertical" transition style


With a Navigation View Controller, I can give a "Cover Vertical" transition style animation. However, having trouble replicating that with a Page View Controller. The only options given in the story board are "Scroll" and "Page Curl". Is there a way to do this programmatically?


UIPanGestureRecognizer at view with UIScrollView


I have a view with UIPanGestureRecognizer.

UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handlePan:)];
    [recognizer setMaximumNumberOfTouches:1];
    [recognizer setDelegate:self];

[self.view addGestureRecognizer: recognizer];

=======
-(void) handlePan:(UIPanGestureRecognizer*)gestureRecognizer
{
  move subview of self.view
}

subview have a scroll view inside. how to capture gesture with event -handlePan: when scroll view is at the end of horizontal scrolling?

enter image description here


Office 365 iOS SDK - How to invoke SharePoint REST API


All the iOS SDK samples provide working code for accessing Mail, Calendar, ODfB FIles, but none show how to access SharePoint list items. So I am trying a simple REST call in Swift, but keep getting the following error:

[0] (null) @"error_description" : @"Unsupported security token.

Here is a subset of my code when my App starts:

var resourceID : String = "http://ift.tt/1qL2pxV"
var authorityURL : String = "http://ift.tt/1t9uKz6"
var clientID : String = "xxd4200eb-7284-41be-a434-abb269b82f0f"
var redirectURI : NSURL = NSURL(string: "http://ift.tt/1RyDJ4q")!

override func viewDidLoad() {
    super.viewDidLoad()

    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var er : ADAuthenticationError? = nil
    var authContext:ADAuthenticationContext = ADAuthenticationContext(authority: authorityURL, error: &er)

    authContext.acquireTokenWithResource(resourceID, clientId: clientID, redirectUri: redirectURI) { (result: ADAuthenticationResult!) -> Void in
        if (result.accessToken == nil) {
            println("token nil")
        } else {
            defaults.setObject(result.accessToken, forKey: "accessTokenDefault")
            defaults.synchronize()
            println("accessToken: \(result.accessToken)")
        }
    }
}

Then, once I get the Token, I invoke the following code that tries an http GET but fails:

    var resolver : MSODataDefaultDependencyResolver = MSODataDefaultDependencyResolver()

    var credentials : MSODataOAuthCredentials = MSODataOAuthCredentials()
    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    credentials.addToken(defaults.objectForKey("accessTokenDefault") as! String)
    var credentialsImpl : MSODataCredentialsImpl = MSODataCredentialsImpl()
    credentialsImpl.setCredentials(credentials)
    resolver.setCredentialsFactory(credentialsImpl)

    //build API string to get a sample list info
    let request = NSMutableURLRequest(URL: NSURL(string: "http://ift.tt/1HfT3Dn")!)
    request.HTTPMethod = "GET"
    let token = defaults.stringForKey("accessTokenDefault")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json; odata=verbose", forHTTPHeaderField: "accept")

    //make the call to the SharePoint REST API
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error:NSError? = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary

        if (jsonResult != nil) {
            //parse the json into File objects in the table view
            let results:NSArray = (jsonResult["d"] as! NSDictionary)["results"] as! NSArray

And this is where it fails with the error message. Monitoring the web traffic, the following is a bit more details about what is going on:

This is my request (RAW):

GET /_api/web?$select=Title HTTP/1.1
Host: mytenant.sharepoint.com
Connection: keep-alive
Proxy-Connection: keep-alive
Accept: application/json; odata=verbose
User-Agent: O365Demo/1 CFNetwork/711.3.18 Darwin/14.3.0
Accept-Language: en-us
Authorization: Bearer Optional("eyJ0eXAiOiJKV1QiLDJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL3VtYWtub3cuc2hhcmVwb2ludC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC81NmZjOTc3OC04YWFjLTQ1ZDItOTMwNS1iOTE3MWZmYWZhOGMvIiwiaWF0IjoxNDM1MjI3Nzk1LCJuYmYiOjE0MzUyMjc3OTUsImV4cCI6MTQzNTIzMTY5NSwidmVyIjoiMS4wIiwidGlkIjoiNTZmYzk3NzgtOGFhYy00NWQyLTkzMDUtYjkxNzFmZmFmYThjIiwib2lkIjoiOGUyZTBlZDQtYmEzNC00YWM4LTkwYmMtNWQ3NGQ3MzE4YjkyIiwidXBuIjoicGllcnJlQHVtYWtub3cuY29tIiwicHVpZCI6IjEwMDMwMDAwODUyMUY3NjYiLCJzdWIiOiJqR3BHQ1VDdDNYTnM2b0pjSkgxVldQOUwyV1JLa3lIOHhxWHlKbVFaSV8wIiwiZ2l2ZW5fbmFtZSI6IlBpZXJyZSIsImZhbWlseV9uYW1lIjoiQm91cmFzc2EiLCJuYW1lIjoiUGllcnJlIEJvdXJhc3NhIiwiYW1yIjpbInB3ZCJdLCJ1bmlxdWVfbmFtZSI6InBpZXJyZUB1bWFrbm93LmNvbSIsImFwcGlkIjoiNmQ0MjAwZWItNzI4NC00MWJlLWE0MzQtYWJiMjY5YjgyZjBmIiwiYXBwaWRhY3IiOiIwIiwic2NwIjoiQWxsU2l0ZXMuTWFuYWdlIEFsbFNpdGVzLlJlYWQgQ2FsZW5kYXJzLlJlYWRXcml0ZSBGaWxlcy5SZWFkIEdyb3VwLlJlYWQuQWxsIEdyb3VwLlJlYWRXcml0ZS5BbGwgTXlGaWxlcy5SZWFkIE15RmlsZXMuV3JpdGUgU2l0ZXMuUmVhZC5BbGwgU2l0ZXMuU2VhcmNoLkFsbCBUZXJtU3RvcmUuUmVhZC5BbGwgVXNlci5SZWFkIFVzZXIuUmVhZFdyaXRlIFVzZXIuUmVhZFdyaXRlLkFsbCIsImFjciI6IjEifQ.aAkaEIFuOeiI0ZRydzaOBTl5wyqLDYBHfvbSj6nZAk4jQKBZF6BhJsAAnhu9qj8oMR2gUdVr3vCNgzefvlZxcf3u0k6R8g4176M-bU3rAABri9DjyaZJ24jMs1u-kL0h5Ee8mvNXSI7BF7Qv9JoeHIiXLei_SXba1s8mhdwMaw9Se9tl8MbBFPLDDBLXUa4YgC_rYWO7G7rw3JEe3GmEV9NffZ7zklXxd55P8fxtbz0-KhI0wbRHIXN69wAuC0jiqhJ4FCCGzLvTuuUbirhURrhi4UizYpLWqqnr0I8zWAMvr8WUXCWtZhPkzOZ5teqbvBwp1UwYui42O6S0PfYKzQ")
Accept-Encoding: gzip, deflate

And finally the RAW response from the site

HTTP/1.1 401 Unauthorized
Server: Microsoft-IIS/8.5
x-ms-diagnostics: 3000006;reason="Token contains invalid signature.";category="invalid_client"
SPRequestGuid: 84c9139d-807c-2000-0e59-4caf75bd097f
request-id: 84c9139d-807c-2000-0e59-4caf75bd097f
SPRequestDuration: 19
SPIisLatency: 1
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 16.0.0.4107
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
WWW-Authenticate: Bearer realm="56fc9778-8aac-45d2-9305-b9171ffafa8c",client_id="00000003-0000-0ff1-ce00-000000000000",trusted_issuers="00000001-0000-0000-c000-000000000000@*,http://ift.tt/1RyDJ4r",authorization_uri="http://ift.tt/1nLu7IU"
Date: Thu, 25 Jun 2015 11:12:40 GMT
Content-Length: 51

{"error_description":"Unsupported security token."}

So there is something obviously wrong with the way I use the Token provided, but with my very limited OAuth2 knowledge and the lack of samples, I am at a lost.

Any help is greatly appreciated!


Using Intents in PhoneGap/Cordova to call default maps app on ios and android platform


I need some help implementing intents in PhoneGap/Cordova for a program that I have running on android and on ios. It's a driver application but I want to link it to the phones default maps app so that it can gps to it once the driver selects a destination. Something Uber like.


Detect when second tableview cell comes into view - then perform an action


I've got a UITableView in a UIViewController, as well as a filter button. I hide the filter button when the user starts to scroll down the list. I want to then show the filter button when the second cell (index 1) is visible. However, I can't get this desired effect, I can only get it to appear when it reaches the top. Here is my code for when it reaches the top (I then show the filter button again).

//determines when the tableview was scrolled
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint currentOffset = scrollView.contentOffset;
     //tableview is scrolled down
    if (currentOffset.y > self.lastContentOffset.y)
      {

    //if the showFilter button is visible i.e alpha is greater than 0
        if (self.showFilter.alpha==1.0) {

            [UIView animateWithDuration:1 animations:^{

                //hide show filter button
                self.showFilter.alpha=0.0;
                //I also adjust the frames of a tableview here
            }];

        }


    }


    //determines if it is scrolled back to the top
    if (self.showFilter.alpha==0.0 && currentOffset.y==0) {
        [UIView animateWithDuration:0.3 animations:^{
            //show filter button
            self.showFilter.alpha=1.0;

          //i also adjust the frames of the tableview here
        }];
    }

    self.lastContentOffset = currentOffset;
}

I have also tried:

if (self.showFilter.alpha==0.0 && currentOffset.y<160)

But it doesn't work to the desired effect as the tableview jumps off the screen. Is there another way to get this desired effect?


Fetching JSON data after failed retrieval


In my application, I am fetching JSON data. Occasionally, the application will fail to fetch it and when I print the responseObject, it returns ( ). I would like to make an if statement so that when this happens, a UIAlertView will show up. Right now, I have an if statement saying that if self.jobs == nil, the alert will come up, but that is not working. I'd really appreciate any help!

- (void)viewDidLoad
{

[super viewDidLoad];

//Fetch JSON
NSString *urlAsString = [NSString stringWithFormat:@"http://ift.tt/1MXKCe4", LANGUAGE, TOWN];
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

//Parse JSON
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
self.jobs  = (NSArray *)responseObject;

if(self.jobs != nil)
{
    [self.tableView reloadData];
}
else
{
    UIAlertView* alert_view = [[UIAlertView alloc]
                               initWithTitle: @"Failed to retrieve data" message: nil delegate: self
                               cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
    [alert_view show];
}
}

//Upon failure
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
 UIAlertView *aV = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:[error localizedDescription] delegate: nil
                                           cancelButtonTitle:@"Ok" otherButtonTitles:nil];
 [aV show];
 }];


Unexpectedly found nil while unwrapping an Optional value while opening UIViewController


I'm doing a simple tableview app with swift, in which you open a new view controller programatically after clicking on a table row:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

//GLobals
@IBOutlet weak var table: UITableView!
//Table View Data

let cats :[String] = ["Gala","Vito","Odin","Ema"]

override func viewDidLoad() {
    super.viewDidLoad()

    table.delegate = self
    table.dataSource = self
}

// MARK:  UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cats.count
}

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

    let row = indexPath.row
    cell.textLabel?.text = cats[row]

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let row = indexPath.row
    let cat : String = cats[row];
    println(cat)

    //Save cat for detail view
    var defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(cat, forKey: "cat")
    defaults.synchronize()


    let detail:Detail = Detail();
    self.presentViewController(detail, animated: true, completion: nil);
}
}

The code in the detail view is the following:

class Detail: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.whiteColor()

    let defeaults = NSUserDefaults.standardUserDefaults()

    let cat = defeaults.stringForKey("cat")

    var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
    label.center = CGPointMake(160, 284)
    label.textAlignment = NSTextAlignment.Center
    label.text = cat

    self.view.addSubview(label)
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let home:ViewController = ViewController()
    self.presentViewController(home, animated: true, completion: nil)
}

However when the app goes back to ViewController I'm having "unexpectedly found nil while unwrapping an Optional value "

the error

I have try some of the other answers to this problem including, warping with if == nil some of the values, but I still can't find what is the problem.

I'm assuming the UIViewController is not loading the UITableViewDelegate and UITableViewDataSource again, but I don't understand why... and how would you load them from another view anyway?


Trouble understanding resuming cells in collection views


I'm following a site to help learn swift and I'm getting confused about this part right here. Basically we added the if cell.imageview.image == nil statement so hat when the collection view loads and you scroll the image doesn't reload the filters. What I don't understand is if you scroll down a cell is reused for the bottom row, now why if I scroll back up doesn't it have to reload the filter? is that data saved somewhere so when I scroll up the properties don't have to repopulate? and If thats the case why would I have to use that if statement at all?

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! FilterCell

    if cell.imageView.image == nil {
    cell.imageView.image = placeholder

    let filterQueue: dispatch_queue_t = dispatch_queue_create("filter queue", nil)

    dispatch_async(filterQueue, { () -> Void in
        let filterImage = self.filteredImageFromImage(self.thisFeeditem.thumbNail, filter: self.filters[indexPath.row])

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            cell.imageView.image = filterImage
            })
        })
    }
    return cell
}


Make NSOperationQueue synchronous


How can I make NSOperationQueue synchronous? I did tried this by subclassing NSOperation and setting "setMaxConcurrentOperationCount" to 1. And also adding dependencies on previous operations using "addDependency" method.

Adding Code:

if(!operationQueue)
{
    operationQueue = [[MyQueue alloc] init];
}
[operationQueue setMaxConcurrentOperationCount:1];
UploadFileOperation *uploadFileOperation = [[UploadFileOperation alloc] initWithObject:someObject];
[operationQueue addOperation:uploadFileOperation];

Now when log the upload progress for two files it shows that both the files are uploading at the same time. Like this: File1 - 17.647026% Uploaded File1 - 18.352907% Uploaded File2 - 0.870381% Uploaded File2 - 1.740762% Uploaded File2 - 2.611142% Uploaded File2 - 3.481523% Uploaded File1 - 19.058788% Uploaded


Complex fetch-request for NSFetchedResultsController


Here's a simplified look for my model:

  • Media has property 'status' that can be either 'Uploading' or 'Uploaded'.
  • User has property 'syncStatus' that be either 'NotSynced' or 'Synced'.
  • ObjectX is a 'linking' object between User and Media
  • User has to-many relationship to ObjectX
  • ObjectX has to-one relationship to Media

Is there any way to use NSFetchedResultsController to fetch all Users that are 'Synced' and whose all media are 'Uploaded'? It would have to update its content also when 'Media' status is changed so that new User should be fetched. I've heard NSFetchedResultsController doesn't work well with such complex fetch requests.

Model Graph


Define iOS Bundle Identifier in a header file


I am trying to maintain two bundle identifiers for the same app: one for the development state, another for the AppStore. This allows me to have both the 'official' version and the development version installed on the exact same device without conflict.

What I need is a simple way to control the bundle identifier through a header file. In Xcode, I have specified the following settings:

  1. Preprocess Info.plist File set to Yes;
  2. Info.plist Preprocessor Prefix File set to ux_defines.h.

The ux_defines.h goes as follows:

// Set this to 0 to switch bundle id to official
#define USE_DEBUG_PRODUCT          1


#if (USE_DEBUG_PRODUCT == 1)
#  define MACRO_APPID com.companyname.appname_dbg
#else
#  define MACRO_APPID com.companyname.appname
#endif

In Info.plist, I have specified the Bundle Identifier as follows:

<key>CFBundleIdentifier</key>
<string>MACRO_APPID</string>

However, when I build for the device, Xcode always gives me an error: Failed to code sign "App Name". On the other hand, everything works smoothly if I keep the bundle identifier hard-coded but define a custom option in Info.plist. For example, the following option:

<key>FooBar</key>
<string>MACRO_APPID</string>

...is correctly preprocessed into:

<key>FooBar</key>
<string>com.companyname.appname_dbg</string>

... or

<key>FooBar</key>
<string>com.companyname.appname</string>

... depending on the value of MACRO_APPID in the header. The error seems only specific to the bundle identifier.

How can I set up the project and avoid these errors?


PFUser logInWithUsernameInBackground in Swift - Missing argument for parameter 'target' call


I am implementing the login function for Parse written in Swift. I am getting an error:

Missing argument for parameter 'target' call

It doesn't seem like I"m missing any parameters though - I'm following the declaration in PFUser.h.

Here is my code:

PFUser.logInWithUsernameInBackground(username, password: userPassword) {
    (user: PFUser?, error: NSError?) -> Void in {
        //More code here
    }
}

Thank you for your help!


iOS/ObjC: "Fallback" tap gesture recognizer?


I have a UIViewController subclass whose view will generally contain some number of UIButtons and other interactive elements which may have one or more gesture recognizes attached to them.

What I'm trying to do is provide some visual feedback in the event that the user taps on a part of the screen that is not interactive. In other words: when the user taps the screen anywhere, if and only if no other control in the view responds to the touch event (including if it's, say, the start of a drag), then I want to fire off a method based on the location of the tap.

Is there a straightforward way to do this that would not require my attaching any additional logic to the interactive elements in the view, or that would at least allow me to attach such logic automatically by traversing the view hierarchy?


CKQueryOperation use with initWithCursor


What am I missing here; I got 125 records on the database, but when I run this I get the same set twice, so initWithCursor doesn't work? Must have done something wrong? missed an important detail here?

-(void)loadStudentControls1n2Picker
{
 __block NSMutableArray *students2load = [[NSMutableArray alloc] init];

    CKDatabase *publicDatabase = [[CKContainer containerWithIdentifier:@"iCloud.blah"] publicCloudDatabase];

    NSPredicate *predicatex = nil;
    predicatex = [NSPredicate predicateWithFormat:@"iBeaconConfig = %@", iBeaconsConfirmed.giReferenceID];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:@"SingleBeaconsDB" predicate:predicatex];
    CKQueryOperation *queryOp =[[CKQueryOperation alloc] initWithQuery:query];
    queryOp.desiredKeys = @[@"record.recordID.recordName",@"Owner"];

    queryOp.recordFetchedBlock = ^(CKRecord *results)
    {
    NSLog(@"Finds ...  %@",results.recordID.recordName);
    if (results[@"Owner"] != nil) {
        [students2load addObject:results[@"Owner"]];
    }
    [iBeaconSingleConfirmed addObject:results];
};

queryOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error)
{
    NSLog(@"students2load  %lu ", (unsigned long)[students2load count]);

    if (cursor != nil) {
        CKQueryOperation *queryOp2 = [[CKQueryOperation alloc] initWithCursor:cursor];
        queryOp2.desiredKeys = @[@"record.recordID.recordName",@"Owner"];
        queryOp2.recordFetchedBlock = ^(CKRecord *results)
        {
            NSLog(@"Finds ...  %@",results.recordID.recordName);
            if (results[@"Owner"] != nil) {
                [students2load addObject:results[@"Owner"]];
            }
            [iBeaconSingleConfirmed addObject:results];
        };
        queryOp2.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error)
        {
            NSLog(@"students2load  %lu ", (unsigned long)[students2load count]);
            [globalPickerConfirmed uploadArray2Picker:students2load];
        };
        [publicDatabase addOperation:queryOp2];
    }


    [self.delegate performSelectorOnMainThread:@selector(refreshPicker:)  withObject:@"Teacher" waitUntilDone:YES];
};

[publicDatabase addOperation:queryOp];
}

I end up with 190 records which is the same set of 95 records x 2.


Only Seen View Animation Active in iCarousel


I have the following implementation.

However, I only want the displayed(active) view animation works, other view animation are disabled unless until user scrolls it. In my current solution, all view animation works at the same time, I need to find a way to stop other view animations.

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{

    if (view == nil){
        if(index==0)
        {
            view=[[UIImageView alloc]initWithFrame:CGRectMake(30, 30, 600, 600)];
            ((UIImageView *)view).animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"Walking-1.png"],
                                 [UIImage imageNamed:@"Walking-2.png"],
                                 [UIImage imageNamed:@"Walking-3.png"],
                                 [UIImage imageNamed:@"Walking-4.png"],
                                 [UIImage imageNamed:@"Walking-5.png"],nil];

            ((UIImageView *)view).animationDuration = 1.5;
            [((UIImageView *)view) startAnimating];
        }

        else if(index==1)
        {
            view=[[UIImageView alloc]initWithFrame:CGRectMake(30, 30, 600, 600)];
            ((UIImageView *)view).animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"Biking-1.png"],
                              [UIImage imageNamed:@"Biking-2.png"],
                              [UIImage imageNamed:@"Biking-3.png"],
                              [UIImage imageNamed:@"Biking-4.png"],                                                   
                              [UIImage imageNamed:@"Biking-5.png"],nil];

            ((UIImageView *)view).animationDuration = 1.5;
            [((UIImageView *)view) startAnimating];
        }

        view.contentMode = UIViewContentModeCenter;
        [view.layer setMasksToBounds:YES];
    }
    return view;
}


How to identify a JSON object using swift and xctest framework?


Using NSJSONSerialization.JSONObjectWithData(..) we can create a JSON object. But is it possible to identify the object type ie. is it a JSON object or not.

I was just trying to check using Swift and XCTestFramework. I tried different ways but no solution still?

Note: After creation of JSON object, I can get the values and can also check the values. XCTest Framework is working fine to test those type of things. But, I stuck to identify the object type.

Anybody has any idea how to identify the JSON object programmatically using Swift and XCTest framework


Create a list of result from Parse.com NSString


I have to create a list of result from a Parse.com database. The field is a NSString, and i'm using Objective-C.

In fact i have this field like a sequence of numbers

Database is like this :
row 1 : 4-7-9-6-18
row 2 : 5-3-8-9-29
row 3 : 32-8-67-3-5
...

Each line, can't have the same number in the sequence.

the goal is to create a list according to the reference sequence.

Let's say that the reference sequence is 3-8-9-44-60

I want to create a list from the Parse.com data like this

Lign 2 has 3 matching numbers
Lign 3 has 2 matching numbers
Lign 1 has 1 matching numbers

Is anyone has i clue, i would be nice to share :)

Thanks in advance for your help ;)


Impact of Xcode build options "Enable bitcode" Yes/No


Yesterday I recognized a ton of warnings regarding the parse.com library:

URGENT: all bitcode will be dropped because '[path]/Parse.framework/Parse(PFAnalytics.o)' was built without bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. Note: This will be an error in the future.

I am aware of the fact that I can remove those warning with this answer but am now wondering if it will have any negative impact in regards to store submission and / or performance of my app.

Xcode informs you regarding bitcode

Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode. [ENABLE_BITCODE]

But I am not getting any useful information out of this text.

  • can I use the above method without any negative impact and without compromising a future appstore submission?
  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?
  • Are there any performance impacts if I enable / disable it?

Whatsapp button working on Android but Blank on IOS


This code is working good on android device like Samsung Galaxy Tab and S3 etc. After selecting a contact, it appears TheTitle -> TheURL.

But it's not working at iOS device like iPhone 6 plus and iPhone 5. After selecting a contact, the TheTitle -> TheURL does not appear, it's just blank.

How can I fix this?

var TheTitle = "post Title Text", TheURL = "http://ift.tt/1GV84XP";

$('#myID').after('<a class="button-share whatsapp" data-action="share/whatsapp/share" href="whatsapp://send?text=' + TheTitle + ' -> ' + TheURL + '" target="_blank">WhatsApp</a>');


Remove an object from an NSUserDefault?


I have added a list object to an NSUserDefault and I need to know how to remove a certain list item. I have the item I need to remove, I just need to know how to remove it from the NSUserDefault.


What is rawId field in addressbook using cordova


I used the cordova plugin to get the address book and did a console.log on the same. In the json i see a field called rawId (apart from id). I see that the id is set (to an integer) but rawId is always 'null'. I also see some threads where its advised to set the rawId to the id value (which tells me data type should be same as id i.e. Integer) before saving the address-book back.

Could someone tell me what rawId field is, and what its data type is?


iOS simulator simulating location updates with customized speed


After doing the research for several hours, I could not find a correct solution to solve my problem. I decide to ask the question myself.

I want to simulate customized location updates in iOS simulator and customize the speed of movement when simulating.

My current way of doing this is to create a customized GPX file and add the GPX file in Xcode->Debug->Simulate Location. The GPX contains several waypoints with coordinates. After simulating the location, the app successfully updates the user location. However, the speed stays constant and it's -1. I tried to add some time tag in the GPX file but it won't change the speed.

Here is part of my GPX file:

<gpx>
    <wpt lon="-117.224240" lat="32.871250">
        <time>2015-06-27T03:08:41.405Z</time>
    </wpt>
    <wpt lon="-117.223830" lat="32.871058">
        <time>2015-06-27T03:08:42.457Z</time>
    </wpt>
    <wpt lon="-117.223630" lat="32.870965">
        <time>2015-06-27T03:08:42.970Z</time>
    </wpt> 
</gpx>

Any suggestions to customize the speed of movement?


how to acces a variable in another class and change its value


I am new to Xcode and Swift so I don't know much about how it all works, but I am trying to make a pop-up view. I want a small view to pop up when I click a button. The view is a View Container (I don't know if that is the best way to do this so if not please tell me a better way to do this) and it starts out hidden then when I click a button it becomes visible. This View Container also has a button that if clicked, it will make the view hidden again.

Here is the code:

import UIKit

class ViewController: UIViewController {

    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.
    }

    @IBOutlet weak var popUpView: UIView!

    @IBAction func startButton(sender: UIButton) {
        popUpView.hidden = false
    }

}

import UIKit

class PopUpViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    override func  prepareForSegue(segue:UIStoryboardSegue,
                                   sender:AnyObject?) 
    {
       // Get the new view controller using segue.destinationViewController.
       // Pass the selected object to the new view controller.
    }

    @IBAction func backButton(sender: UIButton) {
        ViewController().popUpView.hidden = true
    }


}

When I run the app it starts fine because the start button is there and when I click it the pop up shows up but when I click the back button it gives me an error which says that in the console

Unknown class MKMapView in Interface Builder file. fatal error: unexpectedly found nil while unwrapping an Optional value

and in line 31 ViewControler().popUpView.hidden = true

it says Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)

Can someone help. Thanks


Reordering Mailcore2 mail folders


In my iOS project, I integrated mailcore2. I am able to get many features working viewing email, reply email, attach images etc.

I am also getting list of folders from the following code. I want to reorder the standard folders list starting from inbox, sent items, draft, Outbox, Trash and goes on to the last.

NSMutableArray *folderarray = [[NSMutableArray alloc] init];
[[self.imapSession fetchAllFoldersOperation] start:^(NSError *error, NSArray *folders) {
    NSMutableString *folderDetails = [NSMutableString new];
    for (MCOIMAPFolder *fdr in folders) {

        [folderDetails appendFormat:@"\nFolder[%@], flag : %d", fdr.path, fdr.flags];
        [folderarray addObject:fdr.path];
    }
    NSLog(@"Folder Details: %@", folderDetails);
    if (folderarray!=nil) {
        [folderList setAllFolders:folderarray];
        AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        [appDelegate.leftMenu reloadTable];
    }
}];

I am not getting how to reorder/arrange the folders list?


Synonym chains - Efficient routing algorithm for iOS/sqlite


A synonym chain is a series of closely related words that span two anchors. For example, the English words "black" and "white" can connected as:

black-dark-obscure-hidden-concealed-snug-comfortable-easy-simple-pure-white

Or, here's "true" and "false":

true-just=fair=beautiful=pretty-artful-artificial-sham-false

I'm working on a thesaurus iOS app, and I would like to display synonym chains also. The goal is to return minimum spanning tree(s) of a weighted planar graph of word relations. My source is a very large thesaurus with weighted data, where the weights measure similarity between words. (e.g., "outlaw" is closely related to "bandit", but more distantly related to "rogue.")

What optimization strategies do you recommend to make this realistic, e.g., within 5 seconds of processing on a typical iOS device? Assume the thesaurus has half a million terms, each with 20 associations. I'm sure there's a ton of prior research on these kinds of problems, and I'd appreciate pointers on what might be applied to this.

My current algorithm involves recursively descending a few levels from the start and end words, and then looking for intercepting words, but that becomes too slow with thousands of sqlite (or Realm) selects.


Is it ok to submit a build to the app store for testing when a previous build is waiting for review?


I recently submitted an app for review, and it's currently in "Waiting for Review" status.

I'd like to submit a new build and enable it for testing in TestFlight. When I set enable testing on for the new build, the store shows the message:

"are you sure you want to start testing 1.xx.20?  Testing for all builds of 1.xx.19 will stop, and you will send an update to your existing testers"

I don't care about testing the previous version, but I don't want to disrupt the review process. Is it ok to go ahead and enable testing for the new build?


Perform code when frame is changed


I have a custom class that's a subclass of UIView. In the storyboard I set a UIView's class to the custom class. The view in the storyboard has a height constraint so that I can change the height programmatically. (I know it's not the only way, but I think it's the easiest way.)

I want to perform some code in the custom class every time the view's height changes.

I tried the following:

- (void)setFrame:(CGRect)frame  {
    [super setFrame:frame};
    NSLog(@"Frame did change");
}

But this method only runs on startup, not when it's (self) height was changed. How can I perform code anytime it's frame is changed?


Having issues with ios UIWebView scrolling


I have this function I am running in a UIWebView. It works in Android as window.onscroll = scrollFunc; .. with ios I am doing document.ontouchend = scrollFunc; not sure if this is the right method. (I don't think it is, considering I also need to add an onclick method).

The other problem I am having is that ONLY the scroll up action is being called even though the diffY number comes back as negative when scrolling down and positive when scrolling up. I can't figure out why.

var prevDate = Date.now(); var curDate = prevDate;
                                function scrollFunc(e) {
                                    curDate = Date.now();
                                    if((curDate - prevDate) > 1000){ 
                                        if ( typeof scrollFunc.y == 'undefined' ) {
                                            scrollFunc.y=window.pageYOffset;
                                        }
                                        var diffY=scrollFunc.y-window.pageYOffset;
                                        if( diffY<-3 ) {
                                            // Scroll down action here
                                        } else if( diffY>5 ) {
                                            // Scroll up action here
                                        } else {
                                            // First scroll event
                                        }

                                        scrollFunc.y=window.pageYOffset;
                                        prevDate = curDate;
                                    }
                                }


How to make a rest API Call post with multiple parameter, xCode


I am trying to have an API Call post. I can use this post command however my issue is that I have multiple parameters such as, Name, phone number, email, and multiple other private information. I have tried this method in order to get it to work but have not been successful. Thank you in advance for any help!

GET Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://ift.tt/1dQP7EC" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

or

POST URL-Form-Encoded Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://ift.tt/1dQP7EC" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];


AVPlayer not muting with silent switch state


I have a game which is using AVPlayer to stream remote tracks. This music is background audio in the game, so I need it to respect the silent/mute switch on the device.

Following Apple's documentation, I am doing the following:

NSError *error;
NSError *activationError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryAmbient error:&error];
[audioSession setActive:YES error:&activationError];

AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://ift.tt/1qHOCFB"]];
self.player = [[AVPlayer alloc] init];

[self.player replaceCurrentItemWithPlayerItem:item];
[self.player play];

// error = nil, and activationError = nil at this point

I have tried this approach for both remote and local files. The files play and can be heard when the device is silent mode, whereas I'm expecting AVPlayer to mute the playback when the silent switch is on.


AURemoteIO EXC_BAD_ACCESS


In my iOS app I use open-source code (a mix of C++ and Objective-C) in a .mm file to find the max frequency of sound recorded by the mic. However, I'm getting a bad access error about 10% of the time and have no idea how to deal with it, as I'm using a language I'm not familiar with.

The NSLog output is as follows:

ERROR:     [0x19932f310] >aurioc> 806: failed: -50 (enable 3, outf< 2 ch,  44100 Hz, Int8.24, non-inter> inf< 2 ch,  44100 Hz, Int8.24, non-inter>)
2015-06-29 12:31:15.396 XXX[547:138175]  error = couldn't setup remote i/o unit

Here is where the error occurs:

AudioToolbox`AUInputElement::PullInput:
    0x182a821ec <+0>:   stp    x24, x23, [sp, #-64]!
    0x182a821f0 <+4>:   stp    x22, x21, [sp, #16]
    0x182a821f4 <+8>:   stp    x20, x19, [sp, #32]
    0x182a821f8 <+12>:  stp    x29, x30, [sp, #48]
    0x182a821fc <+16>:  add    x29, sp, #48
    0x182a82200 <+20>:  mov    x20, x4
    0x182a82204 <+24>:  mov    x23, x3
    0x182a82208 <+28>:  mov    x21, x2
    0x182a8220c <+32>:  mov    x22, x1
    0x182a82210 <+36>:  mov    x19, x0
    0x182a82214 <+40>:  ldr    w8, [x19, #164]
    0x182a82218 <+44>:  cbnz   w8, 0x182a82224           ; <+56>
    0x182a8221c <+48>:  movn   w0, #0x2a7b
    0x182a82220 <+52>:  b      0x182a822ac               ; <+192>
    0x182a82224 <+56>:  cmp    w8, #1
    0x182a82228 <+60>:  b.eq   0x182a82248               ; <+92>
    0x182a8222c <+64>:  ldrb   w8, [x19, #160]
    0x182a82230 <+68>:  cbz    w8, 0x182a82248           ; <+92>
    0x182a82234 <+72>:  add    x0, x19, #120
    0x182a82238 <+76>:  add    x1, x19, #80
    0x182a8223c <+80>:  mov    x2, x20
    0x182a82240 <+84>:  bl     0x182a810e4               ; AUBufferList::PrepareBuffer(CAStreamBasicDescription const&, unsigned int)
    0x182a82244 <+88>:  b      0x182a82258               ; <+108>
    0x182a82248 <+92>:  add    x0, x19, #120
    0x182a8224c <+96>:  add    x1, x19, #80
    0x182a82250 <+100>: mov    x2, x20
    0x182a82254 <+104>: bl     0x182a811e4               ; AUBufferList::PrepareNullBuffer(CAStreamBasicDescription const&, unsigned int)
    0x182a82258 <+108>: mov    x5, x0
    0x182a8225c <+112>: ldr    w8, [x19, #164]
    0x182a82260 <+116>: cmp    w8, #1
    0x182a82264 <+120>: b.ne   0x182a82284               ; <+152>
    0x182a82268 <+124>: ldr    x0, [x19, #184]
    0x182a8226c <+128>: ldr    w3, [x19, #192]
    0x182a82270 <+132>: mov    x1, x22
    0x182a82274 <+136>: mov    x2, x21
    0x182a82278 <+140>: mov    x4, x20
    0x182a8227c <+144>: bl     0x18298f0ec               ; AudioUnitRender
    0x182a82280 <+148>: b      0x182a8229c               ; <+176>
    0x182a82284 <+152>: ldp    x8, x0, [x19, #168]
    0x182a82288 <+156>: mov    x1, x22
    0x182a8228c <+160>: mov    x2, x21
    0x182a82290 <+164>: mov    x3, x23
    0x182a82294 <+168>: mov    x4, x20
    0x182a82298 <+172>: blr    x8
    0x182a8229c <+176>: ldr    w8, [x19, #164] // EXC_BAD_ACCESS HERE
    0x182a822a0 <+180>: cmp    w8, #0
    0x182a822a4 <+184>: movn   w8, #0x2a7b
    0x182a822a8 <+188>: csel   w0, w8, w0, eq
    0x182a822ac <+192>: ldp    x29, x30, [sp, #48]
    0x182a822b0 <+196>: ldp    x20, x19, [sp, #32]
    0x182a822b4 <+200>: ldp    x22, x21, [sp, #16]
    0x182a822b8 <+204>: ldp    x24, x23, [sp], #64
    0x182a822bc <+208>: ret    

The thing is, this error does not happen in the demo app using the open-source code, so I figure it must be something I added. The only code I added was to the view controller, the code between the three asterisks (***) in here:

#import "LightsViewController.h"

#import "mo_audio.h" //stuff that helps set up low-level audio
#import "FFTHelper.h"


#define SAMPLE_RATE 44100 //22050 //44100
#define FRAMESIZE  512
#define NUMCHANNELS 2

#define kOutputBus 0
#define kInputBus 1



/// Nyquist Maximum Frequency
const Float32 NyquistMaxFreq = SAMPLE_RATE/2.0;

/// caculates HZ value for specified index from a FFT bins vector
Float32 frequencyHerzValue(long frequencyIndex, long fftVectorSize, Float32 nyquistFrequency ) {
    return ((Float32)frequencyIndex/(Float32)fftVectorSize) * nyquistFrequency;
}



// The Main FFT Helper
FFTHelperRef *fftConverter = NULL;



//Accumulator Buffer=====================

// CHANGE "SAMPLE RATE" (?) HERE, I.E., HOW OFTEN THE METHOD IS RUN THAT SAMPLES THE MAX HZ
const UInt32 accumulatorDataLenght = 2048;  //16384; //32768; 65536; 131072;
UInt32 accumulatorFillIndex = 0;
Float32 *dataAccumulator = nil;
static void initializeAccumulator() {
    dataAccumulator = (Float32*) malloc(sizeof(Float32)*accumulatorDataLenght);
    accumulatorFillIndex = 0;
}
static void destroyAccumulator() {
    if (dataAccumulator!=NULL) {
        free(dataAccumulator);
        dataAccumulator = NULL;
    }
    accumulatorFillIndex = 0;
}

static BOOL accumulateFrames(Float32 *frames, UInt32 lenght) { //returned YES if full, NO otherwise.
    //    float zero = 0.0;
    //    vDSP_vsmul(frames, 1, &zero, frames, 1, lenght);

    if (accumulatorFillIndex>=accumulatorDataLenght) { return YES; } else {
        memmove(dataAccumulator+accumulatorFillIndex, frames, sizeof(Float32)*lenght);
        accumulatorFillIndex = accumulatorFillIndex+lenght;
        if (accumulatorFillIndex>=accumulatorDataLenght) { return YES; }
    }
    return NO;
}

static void emptyAccumulator() {
    accumulatorFillIndex = 0;
    memset(dataAccumulator, 0, sizeof(Float32)*accumulatorDataLenght);
}
//=======================================


//==========================Window Buffer
const UInt32 windowLength = accumulatorDataLenght;
Float32 *windowBuffer= NULL;
//=======================================



/// max value from vector with value index (using Accelerate Framework)
static Float32 vectorMaxValueACC32_index(Float32 *vector, unsigned long size, long step, unsigned long *outIndex) {
    Float32 maxVal;
    vDSP_maxvi(vector, step, &maxVal, outIndex, size);
    return maxVal;
}




///returns HZ of the strongest frequency.
static Float32 strongestFrequencyHZ(Float32 *buffer, FFTHelperRef *fftHelper, UInt32 frameSize, Float32 *freqValue) {
    Float32 *fftData = computeFFT(fftHelper, buffer, frameSize);
    fftData[0] = 0.0;
    unsigned long length = frameSize/2.0;
    Float32 max = 0;
    unsigned long maxIndex = 0;
    max = vectorMaxValueACC32_index(fftData, length, 1, &maxIndex);
    if (freqValue!=NULL) { *freqValue = max; }
    Float32 HZ = frequencyHerzValue(maxIndex, length, NyquistMaxFreq);
    return HZ;
}



__weak UILabel *labelToUpdate = nil;
int value;



#pragma mark MAIN CALLBACK
void AudioCallback( Float32 * buffer, UInt32 frameSize, void * userData )
{


    //take only data from 1 channel
    Float32 zero = 0.0;
    vDSP_vsadd(buffer, 2, &zero, buffer, 1, frameSize*NUMCHANNELS);



    if (accumulateFrames(buffer, frameSize)==YES) { //if full

        //windowing the time domain data before FFT (using Blackman Window)
        if (windowBuffer==NULL) { windowBuffer = (Float32*) malloc(sizeof(Float32)*windowLength); }
        vDSP_blkman_window(windowBuffer, windowLength, 0);
        vDSP_vmul(dataAccumulator, 1, windowBuffer, 1, dataAccumulator, 1, accumulatorDataLenght);
        //=========================================


        Float32 maxHZValue = 0;
        Float32 maxHZ = strongestFrequencyHZ(dataAccumulator, fftConverter, accumulatorDataLenght, &maxHZValue);

        //NSLog(@" max HZ = %0.3f ", maxHZ);
        dispatch_async(dispatch_get_main_queue(), ^{ //update UI only on main thread

            ***//labelToUpdate.text = [NSString stringWithFormat:@"%0.3f HZ",maxHZ];

            if (maxHZ > 18950.0f) {
                if (maxHZ < 19050.0f) {
                    value = 0;
                } else if (maxHZ < 19150.0f) {
                    value = 1;
                } else if (maxHZ < 19450.0f) {
                    value = 2;
                }
            }
        });***

        emptyAccumulator(); //empty the accumulator when finished
    }
    memset(buffer, 0, sizeof(Float32)*frameSize*NUMCHANNELS);
}













@interface LightsViewController ()
@property int hzValue;
@property NSTimer *timerWhiteAndOrage;
@property NSTimer *timerRedAndBlue;
@property NSTimer *methodTimer;
@end

@implementation LightsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //labelToUpdate = HZValueLabel;
    _hzValue = value;


    //initialize stuff
    fftConverter = FFTHelperCreate(accumulatorDataLenght);
    initializeAccumulator();
    [self initMomuAudio];

    NSTimer *timer = [NSTimer
                      scheduledTimerWithTimeInterval:(NSTimeInterval)(0.05f)
                      target:self
                      selector:@selector(didReceiveNewMaxHz)
                      userInfo:nil
                      repeats:TRUE];

    timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval) 0.1f];
    _methodTimer = timer;
}

-(void) initMomuAudio {
    bool result = false;
    result = MoAudio::init( SAMPLE_RATE, FRAMESIZE, NUMCHANNELS, false);
    if (!result) { NSLog(@" MoAudio init ERROR"); }
    result = MoAudio::start( AudioCallback, NULL );
    if (!result) { NSLog(@" MoAudio start ERROR"); }
}

-(void) dealloc {
    destroyAccumulator();
    FFTHelperRelease(fftConverter);
}

@end


after adding header cells don't appear


I have big image and after this I have table view. This two elements are on scroll view, and table view :

scrollEnabled = false

I had two cells in my tableView, and their height was counting by function in cell file(cause text in cells is dynamic)

func configure(#comment: Comment) {

    userCommentTextView.text = comment.comment
    userCommentTextView.accessibilityLabel = "Quote Content"
    userCommentTextView.accessibilityValue = comment.comment

}

all was ok, I was counting scrollview size like

scrollView.contentSize.height = tableView.frame.origin.y + tableView.frame.height 

in `func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {} delegate

BUT after I added custom header, all cells are not visible, there is only my header! Why? what is the problem? I checked, there is info for cells. And

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return comments.count
}

is NOT nil. But cellforrowindexpath isn't even executing. Can you help me?


Include of Non Modular Header and file not found for sqlite3.h in Swift with AWS SDK


I'm caught between two very peculiar errors in an iOS Swift project. When I attempt to compile my project, I receive a "Include of Non-modular header" error due to several files in the AWSCore framework of the AWS iOS SDK requiring "sqlite3.h" as an import.

After spending several hours looking for solutions, I eventually copied a copy of the file into the AWSCore folder in my project from Cocoapods, and this removes the issue, compiling my project successfully. However, when I clean the build and attempt to rebuild, I receive a "Lexical or Preprocessor issue - file not found" due to the extra SQLite3.h file.

When I remove it, the compile process will go up to the "include of Non-modular header" error again.

I have already tried nearly all of the common solutions - set include of modular headers to yes, removing the framework and readding, adding "." to the header/framework search paths recursively. I'm now completely stumped, so any help would be greatly appreciated. Thanks!


Firebase facebook login for ios (swift) - Use of unresolved indentifier 'FBSDKLoginManager'


I am just trying to run facebook login via Firebase in my ios app. I have done everything that is mentioned in Firebase`s ios (swift) guide [http://ift.tt/1BWVqou] but I am still facing compilation error:

Use of unresolved identifier 'FBSDKLoginManager'

If I am using:

let facebookLogin = FBSDKLoginManager()

Please note I have downloaded FBSKCoreKit, FBSLoginKit and FBSKShareKit (via cocoapods).

I have also updated my AppDelegate.swift like mentioned in the 7th step from guide above. I have also updated my ...-Bridging-Header.h file like:

#import <Firebase/Firebase.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>

I have also added mentioned frameworks:

libicucore.dylib, libc++.dylib, CFNetwork.framework, Security.framework, SystemConfiguration.framework

Could you please tell me, what I have missed? Thank you for any suggestions.

My pod file:

# Uncomment this line to define a global platform for your project
platform :ios, '8.0'
use_frameworks!

target 'MyTarget' do

pod 'Alamofire', '~> 1.2'
pod 'AEXML'
pod 'AlecrimCoreData', '~> 3.0'
pod 'Firebase', '>= 2.3.2'
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit' 

end

target 'MyProjectTests' do

end


Url Encoding of dictionary with AFNetworking in Objective-c


i have to send POST request in following format to the server:
Content Type: application/x-www-form-urlencoded
Form Key : data
Form Value :

[
 {
   "email" : "test@test.com",
   "password" : "test@test.com"     
 }
]

When i send request by this format in web rest client (Postman/Advance Rest Client),i got success in response.

So how can i send this type of response with AFNetworking?

My code for Objective-c is

NSDictionary *dictLogin = @{@"email":@"test@test.com",@"password":@"test@test.com"};
NSDictionary *dictReq = @{@"data":@[dictLogin]};
NSData *data = [NSJSONSerialization dataWithJSONObject:dictReq options:NSJSONWritingPrettyPrinted error:nil];
NSString *strReq = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:@"http://test.php" parameters:dictReq success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

When i pass dictReq or str as AFNetworking parameter i got response of missing parameter/failure response from server

If it's not possible or hard with AFNetworking , NSUrlConnection/Request will also work

Thanks


Memory Leak and its solutions using weak declaration in Swift


I'm making a match-3 game using SpriteKit. Explanation: http://ift.tt/1wrZ5I3. Please refer to swm93's comment on page 4
This is a tutorial but it seems to have a memory leak in the code. Could anyone possibly download this swift project file and find what causes the memory leak and give possible solutions? The maker of this tutorial said that there is a memory leak in "handleSwipe(swap)" method and that we can fix it by adding "weak" to field declaration. I tried to write "weak var scene: GameScene?" but if I do, it says "scene is nil" even if I initialized it like this: "scene = GameScene(size: skView.bounds.size)" in "viewDidLoad()" function.
Below code is my "GameViewController.swift" and the rest of the classes can be downloaded through my link here.

import UIKit
import SpriteKit
import AVFoundation

class GameViewController: UIViewController {
    // The scene draws the tiles and cookie sprites, and handles swipes.
    var scene: GameScene!

    // The level contains the tiles, the cookies, and most of the gameplay logic.
    // Needs to be ! because it's not set in init() but in viewDidLoad().
    var level: Level!

    var movesLeft = 0
    var score = 0

    @IBOutlet weak var targetLabel: UILabel!
    @IBOutlet weak var movesLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var gameOverPanel: UIImageView!
    @IBOutlet weak var shuffleButton: UIButton!

    var tapGestureRecognizer: UITapGestureRecognizer!

    @IBAction func dismiss(sender: UIButton) {
        self.dismissViewControllerAnimated(true, completion: {})
    }

    lazy var backgroundMusic: AVAudioPlayer = {
        let url = NSBundle.mainBundle().URLForResource("Mining by Moonlight", withExtension: "mp3")
        let player = AVAudioPlayer(contentsOfURL: url, error: nil)
        player.numberOfLoops = -1
        return player
        }()

    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    override func shouldAutorotate() -> Bool {
        return true
    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure the view.
        let skView = view as! SKView
        skView.multipleTouchEnabled = false

        // Create and configure the scene.
        scene = GameScene(size: skView.bounds.size)
        scene.scaleMode = .AspectFill

        // Load the level.
        level = Level(filename: "Level_1")
        scene.level = level
        scene.addTiles()
        scene.swipeHandler = handleSwipe

        // Hide the game over panel from the screen.
        gameOverPanel.hidden = true
        shuffleButton.hidden = true

        // Present the scene.
        skView.presentScene(scene)

        // Load and start background music.
        backgroundMusic.play()

        // Let's start the game!
        beginGame()
    }

    func beginGame() {
        movesLeft = level.maximumMoves
        score = 0
        updateLabels()

        level.resetComboMultiplier()

        scene.animateBeginGame() {
            self.shuffleButton.hidden = false
        }

        shuffle()
    }

    func shuffle() {
        // Delete the old cookie sprites, but not the tiles.
        scene.removeAllCookieSprites()

        // Fill up the level with new cookies, and create sprites for them.
        let newCookies = level.shuffle()
        scene.addSpritesForCookies(newCookies)
    }

    // This is the swipe handler. MyScene invokes this function whenever it
    // detects that the player performs a swipe.
    func handleSwipe(swap: Swap) {
        // While cookies are being matched and new cookies fall down to fill up
        // the holes, we don't want the player to tap on anything.
        view.userInteractionEnabled = false

        if level.isPossibleSwap(swap) {
            level.performSwap(swap)
            scene.animateSwap(swap, completion: handleMatches)
        } else {
            scene.animateInvalidSwap(swap) {
                self.view.userInteractionEnabled = true
            }
        }
    }

    // This is the main loop that removes any matching cookies and fills up the
    // holes with new cookies. While this happens, the user cannot interact with
    // the app.
    func handleMatches() {
        // Detect if there are any matches left.
        let chains = level.removeMatches()

        // If there are no more matches, then the player gets to move again.
        if chains.count == 0 {
            beginNextTurn()
            return
        }

        // First, remove any matches...
        scene.animateMatchedCookies(chains) {

            // Add the new scores to the total.
            for chain in chains {
                self.score += chain.score
            }
            self.updateLabels()

            // ...then shift down any cookies that have a hole below them...
            let columns = self.level.fillHoles()
            self.scene.animateFallingCookies(columns) {

                // ...and finally, add new cookies at the top.
                let columns = self.level.topUpCookies()
                self.scene.animateNewCookies(columns) {

                    // Keep repeating this cycle until there are no more matches.
                    self.handleMatches()
                }
            }
        }
    }

    func beginNextTurn() {
       level.resetComboMultiplier()
        level.detectPossibleSwaps()
        view.userInteractionEnabled = true
        decrementMoves()
    }

    func updateLabels() {
        targetLabel.text = String(format: "%ld", level.targetScore)
        movesLabel.text = String(format: "%ld", movesLeft)
        scoreLabel.text = String(format: "%ld", score)
    }

    func decrementMoves() {
        --movesLeft
        updateLabels()

        if score >= level.targetScore {
            gameOverPanel.image = UIImage(named: "LevelComplete")
            showGameOver()
        }
        else if movesLeft == 0 {
            gameOverPanel.image = UIImage(named: "GameOver")
            showGameOver()
        }
    }

    func showGameOver() {
        gameOverPanel.hidden = false
        scene.userInteractionEnabled = false
        shuffleButton.hidden = true

        scene.animateGameOver() {
            self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideGameOver")
            self.view.addGestureRecognizer(self.tapGestureRecognizer)
        }
    }

    func hideGameOver() {
        view.removeGestureRecognizer(tapGestureRecognizer)
        tapGestureRecognizer = nil

        gameOverPanel.hidden = true
        scene.userInteractionEnabled = true

        beginGame()
    }

    @IBAction func shuffleButtonPressed(AnyObject) {
        shuffle()

        // Pressing the shuffle button costs a move.
        decrementMoves()
    }
}


User tagging and hash tagging


I want to develop a functionality very similar to instagram and Facebook user tagging and hash tagging. How far I have come - 1. I can show suggestions when user enters @ and #.I do it in shouldchangecharacters in range funtion.

  1. I took a dictionary which contains tangle and location of tag in that textfield so I can show it in description in feeds.

Problems - I change color of Tag name but when I write just next to it that character color also changes. When user deletes characters from tagged username I want to delete it whole and location changes for tags so my dictionary become a complete waste. My code works only if user doesn't delete anything but keep writing characters and keep adding tags. Can anyone help me out? Please reply asap. I am stuck


XCode Storyboard Issue


I cant see the Labels, Button etc in the View or their constraints though the Labels and Button appears on the side of the storyboard. And when you run the program in the simulator you can see that they are there. The project from my colleague who uses XCode 6.3.1 and I am using XCode 6.3.2 and he doesn't have this issue. When he updated his to to the same version I have he had the same problem; so he went back to the previous version 6.3.1. Now the problem persisted on my device even when I removed the 6.3.2 and substitute it with 6.3.1

stackoverflow prevented me from uploading the images but I can send it by email to anyone to see the screen shots


Putting Pictures in DynamoDB


I was wondering if it was possible to put pictures into DynamoDB tables from an iOS device. If so I was wondering if someone could provide me with an example using the Swift language as I have no idea where to start.


Captive portal detection, popup implementation?


Based on hostapd, I m building a captive portal. - My Linux Machine provides a Wifi access. - iPad's and Android clients-tablets connect this Wifi.

Generally, any client OS check if a url is reachable, if not : client OS states it is captive, and displays a popup browser window. Popup is used for login, presentation or else.

Id like to display such a popup, to present my machine's service. But I dont get it. I ve avoided the net forward though. All connexions are redirected in the machine localhost website.

Why dont I get such a popup ? How to get it ? How/Where should I implement it on my localhost ?