vendredi 8 mai 2015

iOS using UIGraphicsGetImageFromCurrentImageContext to detect certain pixels on screen

I have a UIView where the user can draw various UIBezierPaths.

I need to analyze the drawn BezierPaths to process certain patterns. I have not found any solution to converting UIBezierPaths to a list of coordinates/points, it seems like this is undoable? It's strange as this data must be stored and used someway to draw the actual paths..

So to bypass this problem i decided to draw the BezierPath with a width of 1px:

[path setLineWidth:1];

And convert my UIView to an UIImage:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

Then i can identify pixels by getting the color for a certain pixel position at the image:

- (UIColor *)colorAtPixel:(CGPoint)point {
    CGImageRef imageRef = [self CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    long bytesPerRow = bytesPerPixel * width;
    int bitsPerComponent = 8;

    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));

    CGContextRef context = CGBitmapContextCreate(rawData,
                                                 width,
                                                 height,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    long byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;
    CGFloat red   = (rawData[byteIndex] * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0 ;
    CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0 ;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;

    byteIndex += 4;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    free(rawData);

    return color;
}

Now my issue is that the image generated is blurry, if a draw a straight 1px BezierPath line and convert this to an UIImage, the line has a width of 3x because of it becomming blurry.

How can i solve this? Is there actually no possible way to convert BezierPaths to a list of coordinates?

Validate an input as JSON notation on iOS

I have an input field on an iOS app that accepts an NSString value. I want to be able to validate the input as a JSON object. For example:

NSString = @"{'foo':'bar'}" //would be validated as JSON notation
NSString = @"Hello world!" //would NOT be validated as JSON

I have tried using the following method:

[NSJSONSerialization isValidJSONObject:(id)obj]

However, it always returns false, even if the string input is something like {'hello':'world'}. Is there anything I'm doing wrong or missing here?

Comparing UI object in ios

I am making a super class to TableView, I will have static TextView in it and also I have TextView in cells.

Then I starting edit my TextView in Cell I assign it to static property of TableView.

Now I need go thought cells subviews, compare 2 textView (static and textView in cell) and find cell.

How can I compare 2 textViews?

I can not compare its texts because then some text did typed I lost event.

Django rotates iphone image after upload

I'm working on a photo website where I want the user to be able to upload a portrait or landscape oriented photo. The maximum width should be 1250px, but the maximum height could be 1667px if it's in portrait mode. When I upload photos in portrait orientation, they show up rotated 90 degrees to the left. Is there a way using Pillow to make sure the photo stays in the correct orientation?

This is my code:

class Result(models.Model):
    result01        = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)
    result01thumb   = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)

    def save(self):
        super(Result, self).save()
        if self.result01:
            size = 1667, 1250
            image = Image.open(self.result01)
            image.thumbnail(size, Image.ANTIALIAS)
            fh = storage.open(self.result01.name, "w")
            format = 'png'
            image.save(fh, format)
            fh.close()

It's important that users be able to upload photos from their phones while they're mobile, so the correct orientation is really important. Is there anything I can do here?

Apple Mach-O linker Error Xcode 6.2

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

I started a new project in Xcode 6.2

Imported AFNetworking using pods.

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 this insane error below.

I'm going crazy with this error.

Please see the image below:

Error Screenshot

Does anyone know how to deal with this?

Thanks in advance.

Setting Device Independent RGB on iOS

I am detecting the rgb of a tapped pixel. Different iPads return slightly different RGB values. I maintain a plist of the different values returned per device and when the app opens it determines the device I am on and uses appropriate values. This is a terrible solution - but it does work.

I now want to fix this properly so I dived into colorspace on iOS. It seems I can use CGColorSpaceCreateCalibratedRGB to set a standard RGB regardless of device so the values returned are the same? Or do I need to convert the

However, I do not know any of the values needed to create a standard color space across devices so my pixel color return values are always the same - or if this is possible.

Some current example return values: iPad 2 r31 g0 b133 a1 iPad Air r30 g0 b132 a1

Can anyone help 'normalize' the pixel return value in a device independent way?

- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
UIColor* color = nil;
CGImageRef inImage = self.image.CGImage;
// Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpha, Red, Green, Blue
CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
if (cgctx == NULL) { return nil; /* error */ }

size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}}; 

// Draw the image to the bitmap context. Once we draw, the memory 
// allocated for the context for rendering will then contain the 
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, inImage); 

// Now we can get a pointer to the image data associated with the bitmap
// context.
unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL) {
    //offset locates the pixel in the data from x,y. 
    //4 for 4 bytes of data per pixel, w is width of one row of data.
    int offset = 4*((w*round(point.y))+round(point.x));
    int alpha =  data[offset]; 
    int red = data[offset+1]; 
    int green = data[offset+2]; 
    int blue = data[offset+3]; 
    ////NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
    //NSLog(@"colors: RGB A %i %i %i  %i",red,green,blue,alpha);
    color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}


// When finished, release the context
CGContextRelease(cgctx); 
// Free image data memory for the context
if (data) { free(data); }

return color;

}

  • (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {

    CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow;

    // Get image width, height. We'll use the entire image. size_t pixelsWide = CGImageGetWidth(inImage); size_t pixelsHigh = CGImageGetHeight(inImage);

    // Declare the number of bytes per row. Each pixel in the bitmap in this // example is represented by 4 bytes; 8 bits each of red, green, blue, and // alpha. bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

    // Use the generic RGB color space. colorSpace = CGColorSpaceCreateDeviceRGB();

    if (colorSpace == NULL) { fprintf(stderr, "Error allocating color space\n"); return NULL; }

    // Allocate memory for image data. This is the destination in memory // where any drawing to the bitmap context will be rendered. bitmapData = malloc( bitmapByteCount ); if (bitmapData == NULL) { fprintf (stderr, "Memory not allocated!"); CGColorSpaceRelease( colorSpace ); return NULL; }

    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here by CGBitmapContextCreate. context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst); if (context == NULL) { free (bitmapData); fprintf (stderr, "Context not created!"); }

    // Make sure and release colorspace before returning CGColorSpaceRelease( colorSpace );

    return context; }

How to Recieve iOS Screen Lock Status

I am a noob just learning to code, so please bear with me.

I am trying to implement a location tracking application and here is my problem. I want to stop GPS updates when iPhone is locked or went into sleep mode.

I have used this discussion as reference point. This is what I have so far.

LockNotifierCallback.h

    #import <Foundation/Foundation.h>
@import CoreFoundation;

@interface LockNotifierCallback : NSObject

+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;

- (void)registerForDeviceLockNotifications;

@end

LockNotifierCallback.m

#import "LockNotifierCallback.h"
@import CoreFoundation;

static void lockcompleteChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    CFStringRef nameCFString = (CFStringRef)name;
    NSString *notificationName =  (__bridge NSString*)nameCFString;
    NSLog(@"Darwin notification NAME = %@",name);

    NSString *timerStatus = @"No Change";
    if ([notificationName isEqualToString:@"com.apple.springboard.lockcomplete"]) {
        timerStatus = @"Yes";
    } else if ([notificationName isEqualToString:@"com.apple.springboard.lockstate"]) {
       timerStatus = @"No";
    }

    NSLog(@"success");
}

@implementation LockNotifierCallback;

+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc {
    return lockcompleteChanged;
}

- (void)registerForDeviceLockNotifications;
{
    NSLog(@"registering for device lock notifications");

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    lockcompleteChanged, // callback
                                    CFSTR("com.apple.springboard.lockcomplete"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    lockcompleteChanged, // callback
                                    CFSTR("com.apple.springboard.lockstate"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}


@end

Xcode compiles this without any error but I don't think it is working as I don't see any logs in Console when I run the app in simulator.

Its a SWIFT project and I have #import "LockNotifierCallback.h" in my bridging header.

Please answer this in detail as I am still learning to code.

Appreciate your help.

EDIT

I am using Objective C only to receive Darwin notification for lockstate (device sleep / awake) to optimize battery life as my app will run in the background, apart from this I am planning to implement location tracking and other functions in SWIFT.

Convert NSString into NSArray in swift

I am getting following response as String:

({latitude="38.54708862304688";longitude="-75.11076354980469";statusColorName=blue;statusID=121;statusName="RespondingToStation";trackLocation=1;},{statusColorName=blue;statusID=2123;statusName="RespondingToScene";},{statusColorName=orange;statusID=185;statusName="AtStation";},{statusColorName=green;statusID=184;statusName=Available;},{statusColorName=red;statusID=183;statusName=Unavailable;})

How to convert it into Array in Swift ?

Scrolling a ViewController Swift

I am trying to make a view controller scrollable because there is not enough room on the screen at one time to fit everything. I have checked out links from Google on how to do this http://ift.tt/1Em0AJc and http://ift.tt/1RimFSU The only thing is that these examples use images while I on the other hand want to use buttons. How would I go about doing this? Thanks!

CGPDFStringGetBytePtr returning incorrect string while scanning pdf

I have one PDF and I am trying to scan PDF using CGPDFScanner. While scanning the pdf, when the word "file" is encountered, the CGPDFStringGetBytePtr API returns "\x02le". PDF is having Type1 font and no ToUnicodeMapping(CMap). Encoding dictionary is not present in the PDF hence using NSUTF8String encoding. However I have tried with all NSMacOSRomanStringEncoding, NSASCIIStringEncoding but had no luck. What can be the problem?

Thanks.

Invalid Signature - Code object is not signed at all. The binary at path [http://ift.tt/1dSpXwT] contains an invalid signature

Well, all was good with submitting to itunes connect, but out of the blue, I just got this email right after uploading my app:

Invalid Signature - Code object is not signed at all. The binary at path [http://ift.tt/1dSpXwT] contains an invalid signature. Make sure you have signed your application with a distribution certificate, not an ad hoc certificate or a development certificate. Verify that the code signing settings in Xcode are correct at the target level (which override any values at the project level). Additionally, make sure the bundle you are uploading was built using a Release target in Xcode, not a Simulator target. If you are certain your code signing settings are correct, choose "Clean All" in Xcode, delete the "build" directory in the Finder, and rebuild your release target.

I've seen that this a commun, infamous error message, and that there is no clear answer to how to fix this.

Here are a few screen shot of my setting:

My certificate: enter image description here

My target code signing settings: enter image description here

enter image description here

The provisioning profile used for submitting: enter image description here

Has anyone an idea on what could be wrong with my settings? Thanks you so much in advance, I'm suppose to release the app this month and I'm freaking out a little bit here...

JSON conversion issue in iOS

I have a json string and another one. i have to append together, send to server and get user id. I am stuck in d middle. Appended string is not getting converted to NSURL.


Here is my code.

- (void)convertingstringtojsondata
{
    NSArray *components = [[NSArray alloc]initWithObjects:ismunicipality,mobilenumberstring,placestring,namestring,  nil];
    NSArray *keys = [[NSArray alloc]initWithObjects:@"is_municipality",@"ph_nbr",@"place",@"reg_name", nil];
    NSLog(@"%@",components);

    NSDictionary *dict = [[NSDictionary alloc]initWithObjects:components forKeys:keys];

    NSLog(@"dict %@", dict);

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:0
                                                         error:nil];
    NSLog(@"JSON DATA %@", jsonData);

    jsonData= jsonData;

  JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

    NSLog(@"JSON STRING%@",JSONString);
}
-(void)sendjsonforregistration
{
 [self convertingstringtojsondata];

    registerwithserverstring = [[NSMutableString alloc]initWithString:@"http://ift.tt/1PtRVKM"];
    [registerwithserverstring appendString:JSONString];

    NSLog(@" appended string %@", registerwithserverstring);

    NSURL *registerURL = [NSURL URLWithString:registerwithserverstring];

    NSLog(@"register URL%@", registerURL);

NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:registerURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData * data, NSError * error) {
    NSData * jsonData1 = [NSData dataWithContentsOfURL:registerURL];

    NSLog(@"%@", jsonData1);

    dataDictionary1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:0 error:&error];

   NSLog(@"DATA DICTIONARY %@", dataDictionary1);

}];
}


Problem:- The registerURL shows null value...

How to hide MPMediaItemPropertyPlaybackDuration slider from locked screen and Control Center?

I'm working on online radio player and need some help. When I set MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo I have title, controls and playback duration slider. I don't need this slider because I have no info about playback duration and moreover it is not a very good looking control. Can somebody prompt me how to hide playback duration slider? And one more question: since the app is online radio player, the user have no ability to forward or rewind the playback, so I want to hide this controls from locked screen and Control Center either. By the way I'm using Swift. Thanks in advance!

best framework for mobile game development

I have made few games in pygame for windows but i want to develop games for android and ios how would pygame be used for that or is there a better way?

Double quotes not showing up in string value inside NSMutableDictionary [duplicate]

I'm trying to post some json content to server using REST apis. On POST request, server is accepting the content value like the one given below in body

{
    "value" = "MyDataValue";
}

But after creating the web request, when I try to log the POST data, what I'm getting in console output is

{
    "value" = MyDataValue;
}

Note: No double quotes around MyDataValue.

On trying the same request with double quotes on chrome poster returns success and without double quotes returns same error in poster also. So I guess adding double quotes would solve the issue.

Here is the code I used for creating the NSDictionary

NSMutableDictionary *parameterDict = [NSMutableDictionary new];  
[parameterDict setObject:@"MyDataValue"forKey:@"value"];

Also, tried adding double quotes using escape character, but returns in 2 double quotes which also returns error. So any other alternative solution would be helpful.

Thanks.

iOS - api to route to a specific location using public transport

I'd like to know if there is an api , which I could use to route to a specific location combined with information belonging to public transport such as departure times or travel times (between train stations).

I read something about Google Transit. But can I use this api for IOS apps? Are there any other (free) api's?

Best regards, Nazar Medeiros

Cropping AVCaptureVideoPreviewLayer output to a square

I am having issues with my AVCaptureVideoPreviewLayer method when grabbing a cropped UIImage of the viewable screen. Currently it is working but not outputting the correct crop that I require.

I am trying to output a square but it (by the looks of it) seems to be giving the full height and compressing the image.

The before image shows the LIVE screen and the after image shows the image once the capture button has been pressed. You can see that it has been changed vertically to fit the square but the height hasn't been cropped vertically.

enter image description here

Capture Image Code

[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

    if (imageSampleBuffer != NULL) {

        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
        [self processImage:[UIImage imageWithData:imageData]];

    }
}];

Cropping code

- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate

        haveImage = YES;

    CGRect deviceScreen = _previewLayer.bounds;
    CGFloat width = deviceScreen.size.width;
    CGFloat height = deviceScreen.size.height;

    NSLog(@"WIDTH %f", width); // Outputing 320
    NSLog(@"HEIGHT %f", height); // Outputting 320

    UIGraphicsBeginImageContext(CGSizeMake(width, width));
    [image drawInRect: CGRectMake(0, 0, width, width)];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGRect cropRect = CGRectMake(0, 0, width, width);

    CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);

    CGImageRelease(imageRef);

    [captureImageGrab setImage:[UIImage imageWithCGImage:imageRef]];

}

Adobe Creative SDK API Key Error

I have configured adobe image SDK in my IOS APP and i have also pass API KEY and Secret Key but while i call edit image am getting Invalid API or Secret Key error here is my code how am passing API KEY and Secret Key

Error:
Invalid API Key and Secret
Please check to make sure you have correctly entered your API key and secret.

Code:

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

    [[AdobeUXAuthManager sharedManager] setAuthenticationParametersWithClientID:@"5587f31263dc4f38b003dc0a5d9a2e5f" withClientSecret:@"81292c83-eec7-42df-be72-334cbc1d6828"];

});

If a user modifies a value, change it in real time on all the apps

This is just a question regarding the concept so I'm not looking on code snippets or something similar because I'm not a programmer but rather...let's say the product owner so I need to know what it takes to achieve this before talking with the developers (which I need to find first).

So here it is: I am thinking on creating an app compatible both with iOS and Android which (amongst other things) will display a value with the following characteristics:

  1. This value will be visible to all the users that are running the app
  2. If a user clicks on a particular button, the value is incremented.
  3. If the value is incremented, all other users will see the new value in real time.
  4. The value can be changed thousands of time per second, deepening on how many users are clicking the button.

Again, I'm mainly interested in the concept so any suggestion will be appreciated. For example since the value will get updated so many times per second, how do I store/modify it? Or how can I push it so fast to all the apps?

Trying to Set Photo As A Mandatory Field during Signup with Pare

I am still new to coding. I have setup my signup screen but I wanted to make it mandatory to upload a profile picture during signup. I've tried to add and "if statement" to show an alert if the photo isn't uploaded but I haven't been successful getting it to work. Any suggestions? Here is my code:

class SignUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet var usernameField: UITextField!

@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet var message: UILabel!
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var firstNameField: UITextField!
@IBOutlet var lastNameField: UITextField!

@IBOutlet var profilePic: UIImageView!




@IBAction func submitDataAction(sender: AnyObject) {


    var userName = usernameField.text
    var userEmail = emailField.text
    var userPassword = passwordField.text
    var firstName = firstNameField.text
    var lastName = lastNameField.text
    var initialImage = UIImage(named: "DidNotLoad")
    var picfile = profilePic.image
    let imageData = UIImagePNGRepresentation(picfile)
    let imageFile = PFFile(data: imageData)







    userEmail = userEmail.lowercaseString

    // Start activity indicator
    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    var newUser = PFUser()
    newUser.username = userName.lowercaseString
    newUser.password = userPassword
    newUser.email = userEmail
    newUser["FirstName"] = firstName
    newUser["LastName"] = lastName
    newUser["ProfilePic"] = imageFile



    newUser.signUpInBackgroundWithBlock {(succeeded: Bool, error: NSError?) -> Void in
        if error == nil {
            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("PushToEventsTableFromSignUp", sender: self)
            }

            self.activityIndicator.stopAnimating()
        }
        else {
            if let message: AnyObject = error!.userInfo!["error"] {
                self.message.text = "\(message)"

            }
        }
    }
}

@IBAction func uploadPhoto(sender: AnyObject) {
    //Create variable for image controller
    var picPhoto = UIImagePickerController()
    picPhoto.delegate = self
    picPhoto.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    picPhoto.allowsEditing = true
    self.presentViewController(picPhoto, animated: true, completion: nil)

}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

   self.dismissViewControllerAnimated(true, completion: { () -> Void in

    })

    profilePic.image = image
}


override func viewDidLoad() {
    super.viewDidLoad()
    self.makingRoundedImageProfileWithRoundedBorder()
    activityIndicator.hidden = true
    activityIndicator.hidesWhenStopped = true


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


private func makingRoundedImageProfileWithRoundedBorder() {
    self.profilePic.layer.cornerRadius = self.profilePic.bounds.size.width/2;
    self.profilePic.layer.masksToBounds = true
   // self.profilePic.clipsToBounds = true

    //Create Border around profile Pic
    self.profilePic.layer.borderWidth = 2.0
    self.profilePic.layer.borderColor = UIColor.whiteColor().CGColor
}

Cannot invoke responseJSON

I'm using Alamofire for my API communication, but xcode shows error when I'm trying to use responseJSON. Anyone can help resolve that? :) enter image description here

Blank Page in UIView

I created a simple app with a web view but it doesn't appear. Only a blank page is shown. My .xib contains the UIWebView

My file ViewController.h:

#import <UIKit/UIKit.h>

@interface TestAViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIWebView *webview;

@end

My file ViewController.m:

#import "TestAViewController.h"

@interface TestAViewController ()

@end

@implementation TestAViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization
    }

    return self;
}

- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.

    //load url into webview
    NSString *strURL = @"http://www.google.it";
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [self.webview loadRequest:urlRequest];


}

@end

Why is this happening? Thanks.

Looking for a framework to add a moveable view in the screen

I have to include to my App a little view with the same behaviour that in FaceTime. When you are having a video call in FaceTime appear a little view with the streaming video of the person who you are talking. I am looking for a framework that let me have a view that it can be moved around the screen like the little view in FaceTime.

Does anyone know of any framework to do this?

Thank you

Xcode: Copy files from one Project to another in same workspace

I am currently working on legacy code for an iPhone application. Someone has implemented a feature in the iPhone and now I am trying to implement it into iPad.

To start with I have decided to drag the files from the iPhone project into the iPad and get it working. Then I am going to find a solution where by both projects can share the same code.

However I have copied the files from the iPhone project into the ipad project and have a problem with the xib. The outlets are still referencing the iPhone version.

So when I remove the IBOutlets from the iPad version the connections still remain because the iPhone xib has not been touched. However when I remove the connections from the iphone project, it also removes the outlets from the ipad version.

These are both separate projects within the same workspace.

I am not sure why this is happening and also is there a way around copy the files without the file referencing the other project?

Notifications from WatchKit extension to App and vice versa (something similar to UILocalNotification?)

Is there an official way to send a notification from the WatchKit extension to the App without using the openParentApplication:reply method?

Ideally I would like to send something similar to a UILocalNotification.

Old Open GL ES 1 draw does not render on iPhone 6 device, but works on other devices and simulators

I'm trying to upgrade an old app that has a small Open GL feature (rolling dice). It works fine on an older iPad, a newer iPad, and all simulators. However, on an actual iPhone 6 device it is blank.

I've stripped down the code such that it only draws a simple horizontal line, and it still renders everywhere but on the iPhone device.

I barely understand Open GL as it is, but the fact that it renders everywhere but on an actual iPhone 6 is really confusing.

Here's the stripped down rendering code.

glLoadIdentity();
glTranslatef(0.0f,0.0f,-12.0f);

glClearColor(1, 1, 1, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // opaque red
const GLfloat line[] = {
    -0.5f, -0.5f, //point A
    0.5f, -0.5f, //point B
};

glVertexPointer(2, GL_FLOAT, 0, line);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_LINES, 0, 2);

Note that if I change the value of glClearColor, it does change the background color so the basic rendering process seems to be working. However, any draws are not visible.

Any suggestions or ideas about what could be the issue?

Size classes iOS 7 compatibility issue

I am trying to use auto layout to to position two views like below picture. I know that with iOS 8 and size classes I can create layout for different layouts and it would work. However I am targeting iOS 7 and according to several posts such as http://ift.tt/1F3OuuT, iPhone landscape mode of size classes will not work for earlier version. So, how can I position those two views on different orientation according to my picture? Thanks.enter image description here

How to get actual first day of the month, possible with my time zone?

I'm trying to get the first day of the month, but I'm getting the UTC value. I think I need my locale date instead?

enter image description here

Why there is still margin on UITableView even after I set constrain to 0

I just bought a book and learn programming IOS in Swift. I want to create a table view list like snapchat: enter image description here

Then I set the all of the constrain of the UITableView to enter image description here0:

However, there is still a margin on left of the table, why?

enter image description here

Shuffle NSMutableArray with 'Shuffle Albums' for up next queue (MediaPlayer)?

I have managed to create an up next queuing system that works (almost) perfectly. I can move, delete and add songs to the list without any issues at all. The only problem i am having is that when the user decides to use a shuffle mode (e.g. MPMusicShuffleMode.Songs), the up next view still displays the old order (assumes shuffle mode is set to off). The app Ecoute has a similar queuing system but it also works when shuffling.

I've realized that Ecoute does not use the MPMusicShuffleMode, if you go into the stock music player after pressing shuffle in Ecoute, it stays the same. I've figured out a way to display the correct order for shuffled songs (just shuffle the NSMutableArray and set this as the new queue). The real problem is how would i shuffle this array when the user wants to 'Shuffle Albums'? The NSMutableArray contains MPMediaItem if that helps.

Many thanks.

EDIT:

This attempt works but the time grows exponentially for the number of songs. 2000 songs took about 25-35 seconds, so very slow.

else if(self.shuffleMode == "Songs"){
        self.shuffleMode = "Albums"
        self.shuffle.setTitle("Shuffle Albums", forState: UIControlState.Normal)
        var queueCopy = NSMutableArray(array: self.queue.items)
        var newQueue = NSMutableArray(array: [])

        var albums = MPMediaQuery.albumsQuery().collections as [MPMediaItemCollection]
        var albumsCopy = NSMutableArray(array: albums)
        shuffleArray(albumsCopy)

        for album in albumsCopy{
            for item in queueCopy{
                if (album.representativeItem!.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString){
                    for(var i = 0; i < album.items!.count; i++){
                        if(album.items![i].valueForProperty(MPMediaItemPropertyTitle) as NSString == item.valueForProperty(MPMediaItemPropertyTitle) as NSString){
                            newQueue.addObject(item as MPMediaItem)
                        }
                    }
                }
            }
        }

        let newQueueToSet = MPMediaItemCollection(items: newQueue)
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        appDelegate.currentQueue = newQueueToSet
        self.queue = newQueueToSet

        self.player.setQueueWithItemCollection(newQueueToSet)

}

EDIT 2:

Managed to get it down to 8 seconds but it's nowhere near Ecoute's 1 to 2 seconds.
8 second version:

        var albumNames = [String]()
        for item in queueCopy{
            albumNames.append(item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString)
        }

        let unique = NSSet(array: albumNames).allObjects as [MPMediaItem]
        var uniqueAlbumNames = NSMutableArray(array: unique)
        shuffleArray(uniqueAlbumNames)

        for name in uniqueAlbumNames{
            for item in queueCopy{
                if item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == name as NSString{
                    newQueue.addObject(item as MPMediaItem)
            }
        }
}

Final Edit:

final piece of code that i'm sticking with. takes about 7-8 seconds for nearly 3000 songs.

    @IBAction func shufflePressed(sender: AnyObject) {

    if self.shuffleMode == "Off"{
        self.shuffleMode = "Songs"
        self.shuffle.setTitle("Shuffle All", forState: UIControlState.Normal)
        self.shuffle.setTitle("Shuffling", forState: UIControlState.Highlighted)


        var queueCopy = NSMutableArray(array: self.queue.items)
        self.unshuffledQueueCopy = self.queue

        shuffleArray(queueCopy)
        let newQueue = MPMediaItemCollection(items: queueCopy)
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        appDelegate.currentQueue = newQueue
        self.queue = newQueue

        self.player.setQueueWithItemCollection(newQueue)

    }
    else if(self.shuffleMode == "Songs"){
        self.shuffleMode = "Albums"
        self.shuffle.setTitle("Shuffle Albums", forState: UIControlState.Normal)

        var queueCopy = NSMutableArray(array: self.queue.items)
        var newQueue = NSMutableArray(array: [])

        var albums = MPMediaQuery.albumsQuery().collections as [MPMediaItemCollection]
        var albumsCopy = NSMutableArray(array: albums)
        shuffleArray(albumsCopy)


        // Takes 8 seconds for 3000 songs

        var albumNames = [String]()

        for item in queueCopy{
            albumNames.append(item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString)
        }

        let unique = NSSet(array: albumNames).allObjects as [MPMediaItem]
        var uniqueAlbumNames = NSMutableArray(array: unique)
        shuffleArray(uniqueAlbumNames)


        for name in uniqueAlbumNames{
            for item in queueCopy{
                if item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == name as NSString{
                    newQueue.addObject(item as MPMediaItem)
                }
            }
        }

        let newQueueToSet = MPMediaItemCollection(items: newQueue)
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        appDelegate.currentQueue = newQueueToSet
        self.queue = newQueueToSet

        self.player.setQueueWithItemCollection(newQueueToSet)

    }
    else if(self.shuffleMode == "Albums"){
        self.shuffleMode = "Off"
        self.shuffle.setTitle("Shuffle", forState: UIControlState.Normal)
        var queueCopy = NSMutableArray(array: self.unshuffledQueueCopy.items)
        var nowPlayingItem = self.player.nowPlayingItem
        for(var i = 0; i < queueCopy.count; i++){
            if(queueCopy[i] as MPMediaItem == nowPlayingItem){
                self.fromIndex = i
            }
        }
        let newQueue = MPMediaItemCollection(items: queueCopy)
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        appDelegate.currentQueue = newQueue
        self.queue = newQueue

        self.player.setQueueWithItemCollection(newQueue)
        self.fromItem = newQueue.items[fromIndex + 1] as MPMediaItem

    }

Cordova App Audio drains battery life but app does not use audio

I have an application which works mostly in background. It uses geolocation and local notifications. When app notifies user it also vibrates. It vibrates every 30minutes / 1 hour.

Application drains the battery quite fast - after ~24 hours I have 50% of the battery (iphone 5C).

In iphone settings, we can check what uses the battery the most. In my case it was this application (72%) with "Audio" note but this app does not use any audio.

Does vibration also count to the "Audio"?

What are the rules to assign the note to the app battery percentage? In this case it was "Audio" but of course not only audio drains battery. Does that note mean what drains the battery the most from each app?

Mutating method sent to immutable object closes app

In my code ,when the user completes a level, it unlocks the next level (out of a total of 15 levels).

However, I have noticed that, when I complete the level, first time, it works, however, when I go back to it and try again, it crashes with this error;

[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object

The code part is this;

//Unlock Next Level
                if (levelNumber != 15) {
                    [m_appDelegate.levels replaceObjectAtIndex:levelNumber withObject:[NSNumber numberWithBool:NO]];
                    [m_appDelegate saveLevels];
                }

If I remove this line;

[m_appDelegate.levels replaceObjectAtIndex:levelNumber withObject:[NSNumber numberWithBool:NO]];

Then the app does not crash, but of course, it does not unlock any further levels.

Some references below that may help;

int levelNumber;
@property (nonatomic, readwrite) int levelNumber;


- (void) actionLockedLevel:(id)sender {
    selectedLevel = ((CCNode*)sender).tag;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Level Locked" message:@"Level is locked. Pass the previous level first." delegate:nil cancelButtonTitle:@"No" otherButtonTitles:nil];
    [alert show];
}

- (void) actionUnlockedLevel:(id)sender {

    CCScene *scene = [CCScene node];
    TimedLevel *layer = [TimedLevel node];
    layer.levelNumber = ((CCNode*)sender).tag;
    [scene addChild:layer];


    [[CCDirector sharedDirector] replaceScene:scene];
}

In AppDelegate.m, levels are called in this;

- (void) loadLevels {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"LEVELS"] == nil) {

        levels = [[NSMutableArray alloc] initWithObjects:
                  [NSNumber numberWithBool:NO],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],
                  [NSNumber numberWithBool:YES],nil];

    } else {
        self.levels = [defaults objectForKey:@"LEVELS"];
    }

    if ([defaults objectForKey:@"LEVELS_PIZZAS"] == nil) {

        levelsPizzas = [[NSMutableArray alloc] initWithObjects:
                        [NSNumber numberWithInteger:200],
                        [NSNumber numberWithInteger:250],
                        [NSNumber numberWithInteger:300],
                        [NSNumber numberWithInteger:350],
                        [NSNumber numberWithInteger:400],
                        [NSNumber numberWithInteger:450],
                        [NSNumber numberWithInteger:500],
                        [NSNumber numberWithInteger:550],
                        [NSNumber numberWithInteger:600],
                        [NSNumber numberWithInteger:650],
                        [NSNumber numberWithInteger:700],
                        [NSNumber numberWithInteger:800],
                        [NSNumber numberWithInteger:900],
                        [NSNumber numberWithInteger:1000],
                        [NSNumber numberWithInteger:1100],nil];

    } else {

        self.levelsPizzas = [defaults objectForKey:@"LEVELS_PIZZAS"]; 
    }

    if ([defaults objectForKey:@"COLLECTED_PIZZAS"] == nil) {
        self.nCurClickAmounts = 0;
    } else {
        self.nCurClickAmounts = [[defaults objectForKey:@"COLLECTED_PIZZAS"] intValue];
    }
    [defaults synchronize];
}

- (void) saveLevels {
    [[NSUserDefaults standardUserDefaults] setObject:levels forKey:@"LEVELS"];
    [[NSUserDefaults standardUserDefaults] setObject:levelsPizzas forKey:@"LEVELS_PIZZAS"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:nCurClickAmounts] forKey:@"COLLECTED_PIZZAS"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

iPhone app on iPad: drawViewHierarchyInRect causes glitch

Running an iPhone app on iPad (iOS 8), using drawViewHierarchyInRect to take a snapshot and do a custom animation between two view controllers. It all runs fine on iPhones but when the app is on iPad (not a universal app, iPhone only) you can see a brief glimpse of a bad snapshot when the animation starts. Basically it seems to take a snapshot of the whole iPad screen, including the black edges, rather than just the simulated iPhone screen. The app also hides the status bar but you can see the status bar in the brief glimpse which means it's probably some kind of bug in iOS as the iPad always shows the status bar for iPhone apps at the top of the screen.

Here's the snapshot code;

UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:update];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Incidentally the flash also occurs when using Airplay to show the app on Apple TV.

objective c Nsstream connect to multiple servers at a time using sockets

I am creating a socket based Ios app using objective c, now my requirement is to connect to two servers at the same time, i am using NSInputStream and NSOutputStream, now i am able to connect to first server and can send and receive data with that server using

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

delegate method but now i have to connect with second server at the same time, means connecting with two server at the same time, please guide me in this.

cellForRowAtIndexPath doesn't get called after calling reloadData in UICollectionView

I have a UICollectionView which uses a subclass of UICollectionViewCell's. Initially, my dataSource contains 5 items, and when the user scrolls down, I fetch more data and add them to my dataSource, then I call reloadData.

But only 3 items are visible. and when I scroll up I can't see the rest of the items, just an empty area. I noticed that cellForRowAtIndexPath only gets called for those 3 items.

When I navigate to my parent view, and back to the view which contains my UICollectionView I can see all the items.

Note: I have implemented layout:sizeForItemAtIndexPath function as each cell has a different size.

Edit:

I partially solved the issue. I had a refreshControl and I called endRefreshing in a background thread.

Am adding images for a better demonstration of what's happening now:

  • The 1st image is before fetching new data, as u can see the data is displayed perfectly.

enter image description here

  • The 2nd image is after fetching new data, as u can see the new items take the exact height of the previous ones (the old cells) and there is an empty area, when I scroll down I can see the rest of the data, and when I scroll back up, the top cells get the right height, as shown in the 3rd image.

enter image description here

enter image description here

After I finish loading new items, I call this method

- (void)updateDataSource
{
   self.collectionViewDataSource = _manager.messages;
   [self.collectionView reloadData];
}

I checked numberOfItemsInSection method, it returns the right number of items.

and here is my layout:sizeForItemAtIndexPath

- (CGSize)collectionView:(UICollectionView *)collectionView layout:   (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:  (NSIndexPath *)indexPath 
{
// Here I am calculating the width and height of the textView which will fit the message

SPH_PARAM_List *feed_data=[[SPH_PARAM_List alloc]init];
feed_data=[self.collectionViewDataSource objectAtIndex:indexPath.row];

if ([feed_data.chat_media_type isEqualToString:kSTextByme]||[feed_data.chat_media_type isEqualToString:kSTextByOther])
{

    NSAttributedString *aString = [[NSAttributedString alloc] initWithString:feed_data.chat_message];

    UITextView *calculationView = [[UITextView alloc] init];
    [calculationView setAttributedText:aString];

    [calculationView setFont:[UIFont systemFontOfSize:14]];
    [calculationView setTextAlignment:NSTextAlignmentJustified];


    CGSize sc = [calculationView sizeThatFits:CGSizeMake(TWO_THIRDS_OF_PORTRAIT_WIDTH, CGFLOAT_MAX)];

    NSLog(@"IndexPath: %li Height: %f", (long)indexPath.row ,sc.height);

    return CGSizeMake(self.view.frame.size.width - (5 * 2), sc.height);

}

return CGSizeMake(self.view.frame.size.width - (5 * 2), 90);

}

Edit 2:

I noticed that layout:collectionViewLayoutsizeForItemAtIndexPath: gets called and it returns the right height, but cellForItemAtIndexPath still deals with an old one.

iOS - Use GCDAsyncSocket to send something to server have some error

I have two client ,one is iOS(Client A) ,another is Jave (Client B) , Client A use for sender and the Client B is receive the data from Client A and print it in console , now I send some String(String and JsonString) to client B , Client B can receieve the message form Client A ,but the console print incomplete

This is my step

1、I define a NSDictionary in iOS

let dict:NSDictionary = ["type":type,"x":point.x,"y":point.y]

2、convent it to json string and append some string in json String

var error:NSError?
let data = NSJSONSerialization.dataWithJSONObject(dict,options:NSJSONWritingOptions.PrettyPrinted, error: &error)
var str = NSString(data: data!, encoding: NSUTF8StringEncoding)
var newStr = return "\(toPort)#\(str!)"

then I print it in iOS console ,It works fine

3、 I convert the string to NSData

let data = newStr.dataUsingEncoding(NSUTF8StringEncoding)

4、send the NSData to server

self.socket!.writeData(data!, withTimeout: self.timeout, tag: 0)

5、only have { displayed in client B ,what happen?

then I try to use jave to achieve the client A , and it works fine in client B

Swift Tableview Cells populated with name and a Int value

I'm trying to build my first app and i'm hitting a wall

I have a view controller and inside this view controller is a UITableView

Now I have been able to populate this view controller using an array.count

I have been able to add an accesory checkmark when i tap on the item to mark sa completed

Now my problem is that i want to tap on an item, mark it as completed AND when completed to have a value written on a label

each cell would have a different Int value

I've read somewhere that to do so i would need to use NSMutableArray but i don't know how to use this

any help would be really appreciated

heres the code :

UPDATED may 8 1215 utc

import UIKit

// --------------------------------------------------------------------------------------------------------------------------\
class ViewController: UIViewController, UITableViewDataSource {                        //class and subclass                  |)
//---------------------------------------------------------------------------------------------------------------------------/
    // Variable and constant, also IBAOutlet


    struct CellData
    {
        var title: String
        var value: String
        var selected: Bool

    }

    var CellData1 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData2 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData3 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData4 = CellData(title: "this is a test", value: "1", selected: true)

    var tableArray: [CellData] = []

    @IBOutlet weak var scoreshow: UILabel!
    @IBOutlet weak var tableView: UITableView!

// --------------------------------------------------------------------------------------

    override func viewDidLoad() {

        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }
//----------------------------------------------------------------------------------------
    // checkmarks when tapped

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark
            {
                cell.accessoryType = .None
                cell.backgroundColor = UIColor.whiteColor()
            }
            else
            {
                cell.accessoryType = .Checkmark
                cell.backgroundColor = UIColor.yellowColor()            }
        }    
    }

//----------------------------------------------------------------------------------------
    //number of sections for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 5
    }
//----------------------------------------------------------------------------------------
    //Calculate the amount of rows

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.tableArray.count;
    }
//----------------------------------------------------------------------------------------
    //Cells text label and config

    func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{


        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
        cell.textLabel!.text = (tableArray[indexPath.row]).title
        scoreshow.text = (tableArray[indexPath.row]).value
        cell.textLabel!.numberOfLines = 0
        cell.selectionStyle = UITableViewCellSelectionStyle.None;

        return cell
 }

//----------------------------------------------------------------------------------------
    //resetbutton

    @IBAction func resetcheck(sender: UIButton) {

            for i in 0...tableView.numberOfSections()-1
            {
                for j in 0...tableView.numberOfRowsInSection(i)-1
                {
                    if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
                        cell.accessoryType = .None
                        cell.backgroundColor = UIColor.whiteColor()
                    }

                }
            }
        }

//----------------------------------------------------------------------------------------

FMOD_DSP_PITCHSHIFT doesn't work for mp3 on iOS

I was trying to implement a function to stretch the Sound speed ,without changing it's pitch and time scale. by documents and tips i can get from google. I try the method to set the frequency of channel to slow of fast the speed.then use FMOD_DSP_PITCHSHIFT to correct the pitch sounds as default;

i was using wav format sound file for test and build function.so far so good until i'm trying to intergrate product resource which sound file was encoded as MP3.awkwad situation occurred , PITCHSHIFT DSP doesn't work at MP3 sound channel. console log looks fine with no exception & error.Same project and setting everything works fine in iOS Simulator.

After some research and experiments, results indicates even m4a works fine at iOS. I use food examples to reproduce this situation. result is same as my project.

I wonder is this some kind of bug? or i missed something at configuration. sample code was based on FMOD Sample project Play stream.

`/*==============================================================================
Play Stream Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2015.

This example shows how to simply play a stream such as an MP3 or WAV. The stream
behaviour is achieved by specifying FMOD_CREATESTREAM in the call to 
System::createSound. This makes FMOD decode the file in realtime as it plays,
instead of loading it all at once which uses far less memory in exchange for a
small runtime CPU hit.
==============================================================================*/
#include "fmod.hpp"
#include "common.h"

int FMOD_Main()
{
    FMOD::System     *system;
    FMOD::Sound      *sound, *sound_to_play;
    FMOD::Channel    *channel = 0;
    FMOD_RESULT       result;
    FMOD::DSP        * pitch_shift;
    unsigned int      version;
    void             *extradriverdata = 0;
    int               numsubsounds;

    Common_Init(&extradriverdata);

    /*
        Create a System object and initialize.
    */
    result = FMOD::System_Create(&system);
    ERRCHECK(result);

    result = system->getVersion(&version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        Common_Fatal("FMOD lib version %08x doesn't match header version %08x", version, FMOD_VERSION);
    }

    result = system->init(32, FMOD_INIT_NORMAL, extradriverdata);
    ERRCHECK(result);

    result = system->createDSPByType(FMOD_DSP_TYPE_PITCHSHIFT, &pitch_shift);
    ERRCHECK(result);


    /*
        This example uses an FSB file, which is a preferred pack format for fmod containing multiple sounds.
        This could just as easily be exchanged with a wav/mp3/ogg file for example, but in this case you wouldnt need to call getSubSound.
        Because getNumSubSounds is called here the example would work with both types of sound file (packed vs single).
    */
    result = system->createSound(Common_MediaPath("aaa.m4a"), FMOD_LOOP_NORMAL | FMOD_2D, 0, &sound);
    ERRCHECK(result);

    result = sound->getNumSubSounds(&numsubsounds);
    ERRCHECK(result);

    if (numsubsounds)
    {
        sound->getSubSound(0, &sound_to_play);
        ERRCHECK(result);
    }
    else
    {
        sound_to_play = sound;
    }

    /*
        Play the sound.
    */
    result = system->playSound(sound_to_play, 0, false, &channel);
    ERRCHECK(result);
    result = channel->addDSP(0, pitch_shift);
    ERRCHECK(result);
            float        pitch = 1.f;
    result = pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
    ERRCHECK(result);
    pitch_shift->setActive(true);
    ERRCHECK(result);
    float defaultFrequency;
    result = channel->getFrequency(&defaultFrequency);
    ERRCHECK(result);
    /*
        Main loop.
    */
    do
    {
        Common_Update();

        if (Common_BtnPress(BTN_ACTION1))
        {
            bool paused;
            result = channel->getPaused(&paused);
            ERRCHECK(result);
            result = channel->setPaused(!paused);
            ERRCHECK(result);
        }
        if (Common_BtnPress(BTN_DOWN)) {
            char valuestr;
            int valuestrlen;
            pitch_shift->getParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, &pitch, &valuestr, valuestrlen);
            pitch+=0.1f;
            pitch = pitch>2.0f?2.0f:pitch;
            pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
            channel->setFrequency(defaultFrequency/pitch);

        }
        if (Common_BtnPress(BTN_UP)) {
            char valuestr;
            int valuestrlen;
            pitch_shift->getParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, &pitch, &valuestr, valuestrlen);
            pitch-=0.1f;
            pitch = pitch<0.5f?0.5f:pitch;
            pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
            channel->setFrequency(defaultFrequency/pitch);
        }

        result = system->update();
        ERRCHECK(result);

        {
            unsigned int ms = 0;
            unsigned int lenms = 0;
            bool         playing = false;
            bool         paused = false;

            if (channel)
            {
                result = channel->isPlaying(&playing);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
                {
                    ERRCHECK(result);
                }

                result = channel->getPaused(&paused);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
                {
                    ERRCHECK(result);
                }

                result = channel->getPosition(&ms, FMOD_TIMEUNIT_MS);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
                {
                    ERRCHECK(result);
                }

                result = sound_to_play->getLength(&lenms, FMOD_TIMEUNIT_MS);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
                {
                    ERRCHECK(result);
                }
            }

            Common_Draw("==================================================");
            Common_Draw("Play Stream Example.");
            Common_Draw("Copyright (c) Firelight Technologies 2004-2015.");
            Common_Draw("==================================================");
            Common_Draw("");
            Common_Draw("Press %s to toggle pause", Common_BtnStr(BTN_ACTION1));
            Common_Draw("Press %s to quit", Common_BtnStr(BTN_QUIT));
            Common_Draw("");
            Common_Draw("Time %02d:%02d:%02d/%02d:%02d:%02d : %s", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : playing ? "Playing" : "Stopped");
            Common_Draw("Pitch %02f",pitch);
        }

        Common_Sleep(50);
    } while (!Common_BtnPress(BTN_QUIT));

    /*
        Shut down
    */
    result = sound->release();  /* Release the parent, not the sound that was retrieved with getSubSound. */
    ERRCHECK(result);
    result = system->close();
    ERRCHECK(result);
    result = system->release();
    ERRCHECK(result);

    Common_Close();

    return 0;
}

`

NSURLSessionDownloadTask initiation in backgroundURLSession completionHandler

I have a situation where I need to download multiple files sequentially as each download depends on its previous downloaded file. (I am processing the file in background itself)

I am using NSURLSessionConfiguration backgroundSessionConfiguration.

There is a scenario where NSURLSessionDownloadTask initiates while the application is in background. This crashes the app with Assertion permittedbackgroundduration.

So, my question is, am I doing wrong by initiating the download task in background???

Thanks in advance, - Satya

Move facial point using opencv

Need to move facial points in the given image.

I need to move the Points ( 2 ) and ( 3 ) to some distance left and right respectively. And point ( 18 ) and ( 19 ) litte bit down. So that I will get an expression like opened mouth. So

  1. How can i move these points?
  2. Can i move these points on the same image or either have to create new one?

enter image description here

and saw the given link but none of one given the answer. So please help me

[http://ift.tt/1RkqEhH]

And i didn't get proper solution from this given url.

How to relocate face points in opencv / face distortion

Thanks in advance.

How to remove black edge on UIImageView with rounded corners and a border width?

I have the following code to make the UIImageView in each of my UITableView's cells have rounded corners:

- (void)awakeFromNib
{
    // Rounded corners.
    [[cellImage layer] setCornerRadius:([cellImage frame].size.height / 2)];
    [[cellImage layer] setMasksToBounds:YES];
    [[cellImage layer] setBorderColor:[[UIColor whiteColor] CGColor]];
    [[cellImage layer] setBorderWidth:3]; // Trouble!
}

I want the images to have a bit of a gap between them, and figured I could make use of the border width to make that happen. Below is an image of what actually happened:

list of users with badly rendered rounded corners

It's that faint black border that I want to know how to get rid of. I'd like to think there's a way of doing it using border width. If not, the best approach might be just to resize the image itself and just set the border width to be 0.

Get the current user custom column data in Swift Parse

As you can see the picture, this is the User class that allow user to login in my ios application

As I login via this user to my own application, after I've login, how do I get the custom column data of this user? For example, I want to get the IntakeCode from this user and show it in text field, how to I do that?

I've try this code, but it doesn't work, it says that

'AnyObject' is not convertible to 'String'; did you mean to use 'as!' to force downcast?

var displayIntake:NSString = PFUser.currentUser()!.objectForKey("IntakeCode")
txtIntake.text = displayIntake as String

Hope that someone can help with it, I just want that IntakeCode from this user show in the textfield.

Fixed positioned elements disappear on page unload

I have a fixed top navigation bar that stays on top of everything while the contents of the page are being scrolled. I noticed that in Chrome for iOS and Safari standalone mode, the fixed bar disappears on page unload before any of the other elements. How to make all the elements, regardless of the positioning, to disappear at the same time?

Demo: http://ift.tt/1EnLVgp Load the page in Chrome for iOS, repeatedly click refresh. Observe how the fixed div vanishes first, then the rest of the content, and finally the page is being redrawn.

OCLint for Xcodebuild Shell Error

I am getting these error after creating a new Aggregate target with below script:

error: oclint not found, analyzing stopped Command /bin/sh failed with exit code 1

Run Script Shell: /bin/sh

Script:

source ~/.bash_profile

hash oclint &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "oclint not found, analyzing stopped"
exit 1
fi

cd ${TARGET_TEMP_DIR}

if [ ! -f compile_commands.json ]; then
echo "[*] compile_commands.json not found, possibly clean was performed"
echo "[*] starting xcodebuild to rebuild the project.."
# clean previous output
if [ -f xcodebuild.log ]; then
rm xcodebuild.log
fi

cd ${SRCROOT}

xcodebuild clean

#build xcodebuild.log
xcodebuild | tee ${TARGET_TEMP_DIR}/xcodebuild.log
#xcodebuild <options>| tee ${TARGET_TEMP_DIR}/xcodebuild.log

echo "[*] transforming xcodebuild.log into compile_commands.json..."
cd ${TARGET_TEMP_DIR}
#transform it into compile_commands.json
oclint-xcodebuild

echo "[*] copy compile_commands.json to the project root..."
cp ${TARGET_TEMP_DIR}/compile_commands.json ${SRCROOT}/compile_commands.json

fi

echo "[*] starting analyzing"
cd ${TARGET_TEMP_DIR}
oclint-json-compilation-database | sed 's/\(.*\.\m\{1,2\}:[0-9]*:[0-9]*:\)/\1 warning:/'

Do I have to change xcode default script to bash? how to do it? Thanks.

Passing the results from findObjectsInBackgroundWithBlock into a variable

I'm trying to pass the result from the query into the variable array

var petitions = [PFObject] = []

Then return that result. How I can do that in Swift?

func getPetitions(employeeId: String, employeeBusiness: String) -> [PFObject] {

    var petitions: [PFObject] = []

    var query = PFQuery(className:"Petitions")
    query.selectKeys(["petitionDate", "availableFrom", "availableTo"])
    query.whereKey("employeeId", equalTo:employeeId)
    query.whereKey("employeeBusiness", equalTo:employeeBusiness)
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            if let objects = objects as? [PFObject] {
                NSLog("Successfully retrieved \(objects.count) petitions.")
                for object in objects {
                    petitions.append(object)
                }
            }
        }
    }

    return petitions
}

objective-c presentViewController position

I have thus UIActivityViewConroller like so:

- (IBAction)Share:(id)sender {

    NSData *pdfData = [NSData dataWithContentsOfFile:self.pdfPath];

    UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:@[pdfData] applicationActivities:nil];

    activityController.popoverPresentationController.sourceView = self.NavBar;

    [self presentViewController:activityController animated:YES completion:nil];

}

My issue is this shows up on the left side of self.NavBar, I would like to position it to the right side, how would I do that ?

Do you need to add your APNS certificate(s) to your local keychain?

When enabling an iOS app for push notifications, you need to create a sandbox SSL certificate to be used by your server to communicate with APNS. Does that sandbox certificate also need to be added to your development computer's keychain?

SLComposeViewController appears slowly

SLComposeViewController takes 3-4 seconds to appear after presenting it. But presentViewController:(UIViewController *) animated:(BOOL) completion:^(void)completion methods completion block gets called immediately. So even if I use a loading indicator it disappears in a blink. The related code is below. Btw I tried dispatch_async it didn't work.

How can I speed up the process do you have any ideas?

SLComposeViewController *shareView = [SLComposeViewController composeViewControllerForServiceType: SLServiceTypeFacebook];
[shareView setTitle:@"Title"];
[shareView setInitialText:@"Description"];
[shareView addURL:[NSURL URLWithString:@"http://www.google.com/"]];
[shareView setCompletionHandler:^(SLComposeViewControllerResult result) {

    switch (result) {
        case SLComposeViewControllerResultCancelled:
        {
            NSLog(@"Facebook Post Canceled");
            break;
        }
        case SLComposeViewControllerResultDone:
        {
            NSLog(@"Facebook Post Successful");
            break;
        }
        default:
            break;
    }
}];

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2.0, [UIScreen mainScreen].bounds.size.height / 2.0);
[activityView startAnimating];
[self.view addSubview:activityView];

[self presentViewController:shareView animated:YES completion:^{
    NSLog(@"Presented facebook");
    [activityView removeFromSuperview];
}];

Passing data to NSObject

I have a HomeModel based app. If a user logs in the app sends his personal code to the next view controller that automatically combines an URL and his personal code. That all works fine. But i need to use that url in the HomeModel file, but if I import the the combined label in the HomeModel file it is empty. Please help me... Here's my code in the ViewController.m:

_labelSceneTwo.text = _labelText;
_urlTextString = _urlText.text;
[_twoCombined setText:[NSString stringWithFormat:@"%@%@", _urlTextString, _labelText]];
_twoCombinedString = _twoCombined.text;
myURL = _twoCombinedString;

And here's my code in the HomeModel.m

ViewController *vc = [[ViewController alloc] init];
_myUrlString = vc.twoCombinedString;
NSURL *jsonFileUrl = [NSURL URLWithString:_myUrlString];

Weird swift behaviour on UITextField

Scenario: I'm setting the text font and size for my UITextField. They also have placeholders.

        let font = UIFont(name: "FlamaSemicondensed-Book", size: 18)

        let attributesDictionary = [NSForegroundColorAttributeName: DefaultSystemColor.DarkRed]

        // Textfileds without borders (and placeholders)
        UsernameTextField.borderStyle = UITextBorderStyle.None
        UsernameTextField.font = font
        UsernameTextField.textColor = DefaultSystemColor.DarkRed
        UsernameTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: attributesDictionary)

I'm configuring (in AppDelegate) a global UI setting, that formats all of my UILabels for a certain font size.

    let font = UIFont(name: "FlamaSemicondensed-Book", size: 13)!
    var labelAppearace = UILabel.appearance()
    labelAppearace.font = font

What's weird in here:

When this UITextField is selected and I'm typing the format is the one I set for the text field (the placeholder are OK too).

But when I leave the field it assumes the behaviour of the UILabel.

I know that because if I comment the UILabel format the textField works properly.

Does anybody have any idea why does it happens?