mercredi 5 août 2015

Errors in retrieving all Parse data from a class


I am retrieving multiple items from Parse and would like to loop through them and add them to an array. Below is my code. I have several errors:

  Cannot invoke append with an argument list of type '(String)'
  Argument for generic parameter 'T' could not be inferred

//end errors

var query = PFQuery(className:"myClass")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

    if error == nil {
    // The find succeeded.
    // Do something with the found objects
    if let objects = objects as? [PFObject] {

                for object in objects {


if let stringObject = object["values"] as? String {
                            self.myArray.append(stringObject)
                        }
                    }

                    }


        } else {

            println("Error: \(error!) \(error!.userInfo!)")
        }
    }

I'd be grateful for any help.

Here is where I create the array:

var myArray: Array = [String]()



via Chebli Mohamed

Store paragraphs of text (including line breaks) in cloud kit and query


I have another newbie question. Hopefully one of you programming gurus can help me with it.

I'm trying to fetch multiple paragraphs of text (e.g. a news article) from CloudKit. I don't know how to format the text so that it includes a line break. I've been told that I should use CKAsset instead of a String on the CloudKit record, but I don't understand how it's supposed to be formatted.

Can anyone help me understand this more?

Thanks in advance.



via Chebli Mohamed

Swift - UIAlertView - Bold text in message


I want to highlight some words in my UIAlertView message, either by making it bold, or, by underline.

let message = "This is normal text.\nBold Title:\n This is normal text"

let alert = UIAlertView(title: "Title", message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")

alert.show()

How could I make "Bold Title" bold (or underline) in message?



via Chebli Mohamed

IOS / Swift2 - List all files in directory


I have a server running nginx. I have a directory in my server where I have several audio files. I replaced my real url by "url".

How can I list them. I want to make a table with all of the files in that directory.

When I print weContent I get:

403 Forbidden

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "url")!

    //self.webView.loadRequest(NSURLRequest(URL: url))

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

        // Will happen when task completes

        if let urlContent = data {

            let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)

            print(webContent)

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.webView.loadHTMLString(String(webContent!), baseURL: nil)

            })

        } else {

            // Show error message

        }

    }

    task.resume()

}

Thank you



via Chebli Mohamed

Why: "Attempting to load .. while deallocating... :UISearchController:"


I have storyboard (ViewControllerA) that has a button that pushes ViewControllerB. VCB is

ViewControllerB has a "back" method as follows: (I've tried this both v1 and v2)

v1:

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
completion:nil];
}

v2:
- (IBAction)back:(id)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

Both methods give the following warning -- as well as some unexpected behavior.

The warning is:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior ()

I used Apple's sample (membership required) to add the new UISearchController.

I tried using the back methods in the base controller, the main controller and the search controller. All give me the same result.

Has anyone come across this? How do I resolve it?



via Chebli Mohamed

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default


When I reference C++ codes in an O-C file, I modify the .m file to .mm according to articles on the internet. Then I build the project. Unfortunately, I got the error msg below:

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default

I have tried all the compilers in Building Settings->C++ Language but they don't work. I have tried multiple syntaxes but they didn't work.

Why is this happening and how can I solve it?



via Chebli Mohamed

How can i check image contain data or not in this Response


This is my response API. The image data dynamically changes,with more image at a time or else no image at a time. I have check as ([image_array count]==0) but app crash due to empty array.
Error

reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x0243edf6 __exceptionPreprocess + 182

API RESPONSE


{
    response =     {
        Details =         {
            ID = 4;
            address = "";
            ancestors =             (
            );
            "comment_count" = 0;
            "comment_status" = closed;
            description = "";
            "description_pt" = "";
            duration = 2;
            "event_address" = "";
            "event_location" = ",";
            "event_location_option" = "";
            "event_place_address" = "";
            "event_place_email" = "";
            "event_place_location" = "";
            "event_place_phone" = "";
            "event_place_website" = "";
            filter = raw;
            guid = "";
            images =             (
            );
            "like_count" = 0;
            "like_status" = FALSE;
            location = "";
            "menu_order" = 0;
            "ping_status" = closed;
            pinged = "";
            "place_event_count" = "";
            "place_event_id" = "";
            "place_id" = "";
            "post_author" = 5;
            "post_category" =             (
            );
            "post_content" = "";
            "post_content_filtered" = "";
            "post_date" = "2015-07-31 ";
            "post_date_gmt" = "2015-07-31 ";
            "post_excerpt" = "";
            "post_mime_type" = "";
            "post_modified" = "2015-07-31 ";
            "post_modified_gmt" = "2015-07-31 ";
            "post_name" = 48;
            "post_parent" = 0;
            "post_password" = "";
            "post_status" = publish;
            "post_title" = "";
            "post_type" = events;
            "tags_input" =             (
            );
            time = "17:50:30";
            title = "";
            "title_pt" = "";
            "to_ping" = "";
            video = "";
            website = "";
        };
        Message = "Post Details";
        httpCode = 10;
    };
}



via Chebli Mohamed

How to connect to Virtual MIDI host on iOS


I am developing a MIDI controller iOS app. So far I have managed to connect it to GarageBand on my Mac over wifi using NSNetServiceBrowser to find service with type "_apple-midi._udp" and then creating MIDI connection for the found service.

Now I want to integrate my app with Virtual MIDI host app like SampleTank. Googling for a few days, I can't find any examples of how to achive this. I need to get the list of all available MIDI hosts on the device and connect to one.

Could you please give me a direction where to find required info to accomplish my task?



via Chebli Mohamed

CMSampleBufferRef to aac ADTs and RTP payload


Need help on below queries..

I m trying to build an RTSP based application for mac. I am capturing audio through the mac inbuilt mic using AVCaptureSession class.

I am using following code to set the delegate of the audiooutput

AVCaptureAudioDataOutput *audioOut = [[AVCaptureAudioDataOutput alloc] init];

dispatch_queue_t audioCaptureQueue = dispatch_queue_create("Audio Capture Queue", DISPATCH_QUEUE_SERIAL);
[audioOut setSampleBufferDelegate:self queue:audioCaptureQueue];
if ([self.captureWebCamSession canAddOutput:audioOut])
    [self.captureWebCamSession addOutput:audioOut];

AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;

NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                                [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                                [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,
                                [ NSNumber numberWithInt: 128000 ], AVEncoderBitRateKey,nil];

audioOut.audioSettings = outputSettings;

Now I am getting aac encoded buffer in the

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection

Now can someone tell me how can i get the aac adts data from the sample buffer and than convert it into the RTP payload which can be transferred to rtsp server for broadcasting.

Thanks in advance for any help..



via Chebli Mohamed

Keyboard Extension doesn't install the main app


I have created new schemes for both main app and extension.
When I run the main app on device, it works as expected. But when I run the keyboard extension it runs but it is not under debug, and if I remove the app previously then it wouldn't be installed. Can anybody explain what's happened?



via Chebli Mohamed

UIPickerView showing empty grey box Swift


I haven't a whole lot of code, so I might as well copy it here.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{

    var buildings = ["BankBuilding", "Cinema" , "CornerShop", "Greg's House"]

    @IBOutlet weak var buildText: UITextField!

    var buildPickers:UIPickerView = UIPickerView()

    override func viewDidLoad() {
        super.viewDidLoad()

        buildPickers = UIPickerView()
        buildPickers.delegate = self
        buildPickers.hidden = true;
        buildText.inputView = buildPickers
        buildText.text = buildings[0]        
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        println("Count: \(buildings.count)")
        return buildings.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        println("creating title: \(buildings[row])")
        return buildings[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        println("Selected: \(buildings[row])")
        buildText.text = buildings[row]
        buildPickers.hidden = true;
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        buildPickers.hidden = false
        return false
    }
}

The print statements are correct. For numberOfRows... and titleForRow it is printing the correct Strings.

But there is no prints for didSelectRow because, well, I can't select a row.

This is what I get:

enter image description here

You can ignore the Google Map in the background, that shouldn't interfere with the Picker View and is just set up in the StoryBoard.

The Grey window appears when I click on the textField but never shows any content. But the print statements say otherwise.

Does anyone know why this is the case?



via Chebli Mohamed

NSOperationQueue with operation block not working as desired in SWIFT


I have to check series of operations sequentially. but in case of any operation failed i need to call other operation before executing listed operation in queue.

for example:

priority 1 : Fetch all companies lookups
priority 2 : Fetch all regions
priority 3...N : Fetch all cities individually for each region

in each operation i pass one key which valid only for 2 hours... suppose key was generated on 10am and i will start fetching data from server and it will take 15 mins to fetch all data completely.

but the problem is i have started fetching data on 11:59 am and during fetching information key expired. so i need to send one more request to get key and proceed further for next operations.

so it looks like:
priority 1 : Fetch all companies lookups with key
priority 2 : Fetch all regions (i.e. 4 Regions available) with key
   priority 3 : Fetch all cities for region 1 with key
   priority 4 : Fetch all cities for region 2 with key (here key is expire) so for taking new key need to add new operation here, which fetch new key which is valid again for next two hours.
   priority 5 : Fetch all cities for region 3 with new key
   priority 6 : Fetch all cities for region 4 with new key

Code which i have tried:

var queue = NSOperationQueue.mainQueue()
queue.addOperationWithBlock({
  callService(“http://dsn/FetchingCompanyData”)
}

queue.addOperationWithBlock({
  callService(“http://dsn/FetchingRegionData”)
  //get region List here
  for region in regions{
   queue.addOperationWithBlock({
    callService(“http://dsn/FetchingCities?region=\(region.code)”)
    //check in response if response return message like KEY_EXPIRE
    if(error){
      queue.addOperationWithBlock({
        var newKey = callService(“http://dsn/FetchingCities?region=\(region.code)”)
        setKeyToCache(newKey)
      })
    }
  }
}
}

fun callService(urlStr: String){
    let myURL = NSURL(string: urlStr)!
    var key = getKeyFromCache()
    var request = NSMutableURLRequest(URL: myURL)
    var errorHandling = ErrorHandling()
    request.HTTPMethod = "POST"
    request.timeoutInterval = 10000.0
    request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
    request.addValue("application/xml", forHTTPHeaderField: "Accept")
    request.setValue("Basic \(key)", forHTTPHeaderField: "Authorization")

    NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in ..}
}

this code is not working as desire.

it adding operations in queue as below:

Queue:
Operation 1: Fetch companies
Operation 2: Fetch Regions
Operation 3: Fetch cities for region 1
Operation 4: Fetch cities for region 2
Operation 5: Fetch cities for region 3
Operation 6: Fetch cities for region 4
Operation 7: Fetch new key for region 1
Operation 7: Fetch new key for region 2
Operation 7: Fetch new key for region 3
Operation 7: Fetch new key for region 4

instead of this i want sequence of operations as below.

 Operation 1: Fetch companies
    Operation 2: Fetch Regions
    Operation 3: Fetch cities for region 1
    Operation 4: Fetch cities for region 2
    Operation 5: Fetch new key for region 2
    Operation 6: Again Fetch cities for region 2
    Operation 7: Fetch cities for region 3
    Operation 8: Fetch cities for region 4

Any help will be more appreciated.



via Chebli Mohamed

hmac nsdictionary - express req.body


i am trying to do a generic - hmac verification with an iOS app and an express node.js app.

generating the hmac using given samples at: http://ift.tt/1P42qG1

having the following problem: subclassed AFHTTPRequestOperationManager to gain access to POST: i want to hmac the nsdictionary parameters.

so convert the nsdicionary to json - hmac it - and set hmac header in request. on the receiver side, i use crypto-js and express to access the req.body - and hmac the json object.

problem is! - thos keys are not in same oder, even if i force the sort on the keys in nsdictionary, the transoformed json does not come in the order way.

after hours of googling i accepted that json objects cannot be orderd, in an reliable way.

so what is the best-practice to hmac an nsdictionary, by ignoring the order? (i could hmac on only a few keys, but that would be way to less generic, mean adding a dictionary key would require code change in ios and express)

generating the hmac only based on the URI - works fine, but its a way to open :)

UPDATE: to be a bit more specific.

on the app i transform my nsdictionary to json by and then calculate the hmac of the json_string

NSDicationary * dic = @{@"key1", "value1",@"key2", "value2"} 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

NSString * json_str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]

and i do a AFNetworking POST request calling passing my nsdictionary as parameters:

- (AFHTTPRequestOperation *)POST:NSString *)URLString parameters:(id)parameters   success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

on the receiver app (node.js/express) i get the ctx.req.body containing the javascript object from the POST request -> but here it does not have the same order as in the json encoded string from the app (and i have not found a way to preserve order)

as i am not knowing what keys are in nsdicationary a static key-hmac would not work.

regards helmut



via Chebli Mohamed

iCarousel inside Tableview


I am trying to add iCarousel inside a tableview. I have followed http://ift.tt/1N9xH9e guide and amend it to iCarousel instead of collection view. Problem is the items in the iCarousel are not scrolling. Anyone tried same thing before? Please help.

enter image description here



via Chebli Mohamed

can I use UIDocumentPickerExtensionViewController without iCloud?


Actually I want to use google drive to store and access my files for my application. But I am not getting the how to do that without enabling iCloud. And also I am new to extensions and this document picker so it is already bit difficult to understand those things. sample codes will be easier to understand.



via Chebli Mohamed

Force a specific CLHeading value


In order to perform tests, I would like to force specific heading values to check if my app correctly processes them. Yet there are no instructions on the Apple website about how to manually create a CLHeading and the practice is even discouraged . Is there a way to do so or anyway to force CLLocationManager to deliver a specific heading value?



via Chebli Mohamed

Creating a iOS scrollable timeline view


I'm trying to create a timeline view in iOS that can be scrolled both horizontally (time) and vertically (cities). I'm having trouble finding if there is something made from before that I can look at for help.

The timeline view is a view that have date and time going horizontally and you can move time back and forward with moving finger on the horizontal axis. Vertically you can go future down to see the different rows (cities).

Timeline looks something like this:

Wed 4 Aug
---------
City A
01    02    03    04    ... time continues ->

City B
02    03    04    05

...(cities continue vertically)

What is the best approach to this? I been thinking about UIScrollView, but I have rows (cities) that need to be in place while changing the time.

I have experimented with UIView that has it's own drawRect but that seems less than brilliant to redraw each time user moves a little bit and sounds very heavy on the hardware.

I'm also thinking that different layers of UIViews could solve this, with top layer having the city names and the bottom layer being scrolled, but how could I solve the vertical scrolling?



via Chebli Mohamed

UIButton click event crash after adding the viewcontroller's view as a sub view


I want to add several ViewController's views as sub views of my another viewcontroller. So I have done like this inside my parent viewController.

-(void)MakeDisplayArea
{
vwDisplayArea=[[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h-scrolTab.frame.size.height)];

[self.view addSubview:vwDisplayArea];
}





-(void)ProfClick :(id)sender

{

    [self MakeDisplayArea];
    ProfileViewController *profviewcontroller=[[ProfileViewController alloc] initWithNibName:@"ProfileViewController" bundle:nil];
    profviewcontroller.view.frame=vwDisplayArea.frame;
    [profviewcontroller.view setBackgroundColor:[UIColor clearColor]];
    [vwDisplayArea addSubview:profviewcontroller.view];

}

Then inside the profViewcontroller ViewDidLoad methods I am generating a button and set the target like this.

UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(10, 60, 100, 30)];
[btn setTitle:@"Button Test" forState:UIControlStateNormal];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)btnClick :(id)sender
   {

      NSLog(@"button clicked-------");
   }

I can see the button is appearing on that profViewcontroller that I loaded as a sub view, but when I click the button the app is crashing. What is the correct way add that viewcontroller as a subview on my first viewcontroller. Please help me.

Thanks



via Chebli Mohamed

Passing userID with photo POST Swift


I have an upload function that sends a photo to my server using a POST method. I now want to also include a variable userID (currentUser) in this service. I have the following code, but when i switch let param = ["userId" : "1"] to something like let param = [currentUser] i get an error. currentUser is declared as a String which is what the function calls for so I cant really figure out whats wrong.

func myImageUpLoadRequest(){
        let myUrl = NSURL(string: "http://ift.tt/1Hq3Qo1");

        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        let param = ["userId" : "1"]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

        if(imageData==nil)  { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: "imagefile", imageDataKey: imageData, boundary: boundary)



via Chebli Mohamed

How to add UIButton Programmatically from a NSObject Class


I am trying to create a uibutton in a NSObject class. i get the error " Use of unresolved identifier 'view'". i figured that it needs to have UIViewController for it to work.

is there a work around so that i create multiple buttons with just this on multiple view controllers. what am i missing?

func createButton () {
    let button = UIButton();
    button.setTitle("Add", forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    button.frame = CGRectMake(15, -50, 200, 100)
    view.addSubview(button)
}



via Chebli Mohamed

I am following the tutorial given here with some of my own modification to create a Container View Controller that should hold three different View Controllers.

But when I run the app the views are not getting swapped properly and also crashes. Here is the log report:

2015-08-05 15:25:27.564 VUTEk Go[5589:327605] -[RightViewController shouldPerformSegueWithIdentifier:sender:]
2015-08-05 15:25:27.565 VUTEk Go[5589:327605] -[RightViewController prepareForSegue:sender:]
2015-08-05 15:25:27.566 VUTEk Go[5589:327605] -[LogContainerViewController prepareForSegue:sender:]
2015-08-05 15:25:29.339 VUTEk Go[5589:327605] TAB2
2015-08-05 15:25:29.340 VUTEk Go[5589:327605] -[LogContainerViewController swapViewControllers:]
2015-08-05 15:25:29.341 VUTEk Go[5589:327605] -[LogContainerViewController prepareForSegue:sender:]
2015-08-05 15:25:29.341 VUTEk Go[5589:327605] -[LogContainerViewController swapFromViewController:toViewController:]
2015-08-05 15:25:31.363 VUTEk Go[5589:327605] TAB3
2015-08-05 15:25:31.363 VUTEk Go[5589:327605] -[LogContainerViewController swapViewControllers:]
2015-08-05 15:25:31.363 VUTEk Go[5589:327605] -[LogContainerViewController swapFromViewController:toViewController:]
2015-08-05 15:25:31.407 VUTEk Go[5589:327605] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Children view controllers (null) and <StatusLogViewController: 0x7fcbac90ca30> must have a common parent view controller when calling -[UIViewController transitionFromViewController:toViewController:duration:options:animations:completion:]'

Here is my interface file:LogContainerViewController.h

#import <UIKit/UIKit.h>

@interface LogContainerViewController : UIViewController
- (void)swapViewControllers:(int) index;
@end

And my implementation file:LogContainerViewController.m

#import "LogContainerViewController.h"


#import "ErrorLogViewController.h"
#import "WarningLogViewController.h"
#import "StatusLogViewController.h"

#define SegueIdentifierFirst @"errorSegue"
#define SegueIdentifierSecond @"warningSegue"
#define SegueIdentifierThird @"statusSegue"


@interface LogContainerViewController ()
@property (strong, nonatomic) NSString *currentSegueIdentifier;
@property (strong, nonatomic) ErrorLogViewController* errorViewController;
@property (strong, nonatomic) WarningLogViewController* warningViewController;
@property (strong, nonatomic) StatusLogViewController* statusViewController;
@property (assign, nonatomic) BOOL transitionInProgress;
@end

@implementation LogContainerViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.transitionInProgress = NO;
    self.currentSegueIdentifier = SegueIdentifierFirst;
    [self performSegueWithIdentifier:self.currentSegueIdentifier sender:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"%s", __PRETTY_FUNCTION__);

    // Instead of creating new VCs on each seque we want to hang on to existing
   // instances if we have it. Remove the second condition of the following
  // two if statements to get new VC instances instead.
  if ([segue.identifier isEqualToString:SegueIdentifierFirst]) {
     self.errorViewController = segue.destinationViewController;
  }

  if ([segue.identifier isEqualToString:SegueIdentifierSecond]) {
    self.warningViewController = segue.destinationViewController;
  }
  if ([segue.identifier isEqualToString:SegueIdentifierThird]) {
    self.statusViewController = segue.destinationViewController;
  }

 // If we're going to the first view controller.
 if ([segue.identifier isEqualToString:SegueIdentifierFirst]) {
    // If this is not the first time we're loading this.
    if (self.childViewControllers.count > 0) {
        [self swapFromViewController:[self.childViewControllers objectAtIndex:0] toViewController:self.errorViewController];
    }
    else {
        // If this is the very first time we're loading this we need to do
        // an initial load and not a swap.
        [self addChildViewController:segue.destinationViewController];
        UIView* destView = ((UIViewController *)segue.destinationViewController).view;
        destView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        destView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        [self.view addSubview:destView];
        [segue.destinationViewController didMoveToParentViewController:self];
    }
}
// By definition the second view controller will always be swapped with the
// first one.
else if ([segue.identifier isEqualToString:SegueIdentifierSecond]) {
    [self swapFromViewController:[self.childViewControllers objectAtIndex:0] toViewController:self.warningViewController];
}
else if ([segue.identifier isEqualToString:SegueIdentifierThird]) {
    [self swapFromViewController:[self.childViewControllers objectAtIndex:0] toViewController:self.statusViewController];
}
}

- (void)swapFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController
{
 NSLog(@"%s", __PRETTY_FUNCTION__);

toViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

[fromViewController willMoveToParentViewController:nil];
[self addChildViewController:toViewController];

[self transitionFromViewController:fromViewController toViewController:toViewController duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:^(BOOL finished) {
    [fromViewController removeFromParentViewController];
    [toViewController didMoveToParentViewController:self];
    self.transitionInProgress = NO;
}];
}

- (void)swapViewControllers:(int) index
{
NSLog(@"%s", __PRETTY_FUNCTION__);

if (self.transitionInProgress) {
    return;
}

self.transitionInProgress = YES;
//self.currentSegueIdentifier = ([self.currentSegueIdentifier isEqualToString:SegueIdentifierFirst]) ? SegueIdentifierSecond : SegueIdentifierFirst;

if([self.currentSegueIdentifier isEqualToString:SegueIdentifierFirst] && index==0){
    self.currentSegueIdentifier = SegueIdentifierFirst;
}else if ([self.currentSegueIdentifier isEqualToString:SegueIdentifierSecond] && index==1){
    self.currentSegueIdentifier = SegueIdentifierSecond;
}
else{
    self.currentSegueIdentifier = SegueIdentifierThird;
}




if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierFirst]) && self.errorViewController && index==0) {
    [self swapFromViewController:self.warningViewController toViewController:self.errorViewController];
    return;
}
if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierThird]) && self.statusViewController && index==2) {
    [self swapFromViewController:self.warningViewController toViewController:self.statusViewController];
    return;
}


if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierSecond]) && self.warningViewController && index==1) {
    [self swapFromViewController:self.errorViewController toViewController:self.warningViewController];
    return;
}

if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierThird]) && self.statusViewController && index==2) {
    [self swapFromViewController:self.errorViewController toViewController:self.statusViewController];
    return;
}
if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierFirst]) && self.errorViewController && index==0) {
    [self swapFromViewController:self.warningViewController toViewController:self.errorViewController];
    return;
}
if (([self.currentSegueIdentifier isEqualToString:SegueIdentifierSecond]) && self.errorViewController && index==1) {
    [self swapFromViewController:self.statusViewController toViewController:self.warningViewController];
    return;
}



[self performSegueWithIdentifier:self.currentSegueIdentifier sender:nil];
}

@end

I want to load these view when I select a segment in my UISegmented View. The action for that is :

- (IBAction)printerLogSegmentChanged:(id)sender {
UISegmentedControl *s = (UISegmentedControl *)sender;

if (s.selectedSegmentIndex == 0)
{
    NSLog(@"TAB1");
    [self.containerViewController swapViewControllers:0];
}
else if (s.selectedSegmentIndex == 1){
    NSLog(@"TAB2");
    [self.containerViewController swapViewControllers:1];
}
else if (s.selectedSegmentIndex == 2){
    NSLog(@"TAB3");
    [self.containerViewController swapViewControllers:2];
}
else{
    NSLog(@"TAB NOT Working");
}

}

But I think there is something wrong with logic of - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender; that I am using.

Any help will really be appreciated as I have been stuck on this for more than two hours and all similar question couldn't help me.

I am sharing a screen shot of my appenter image description here

As you can see in the above screenshot that it swaps the wrong child view and sometime also crashes.

Thanks in advance!



via Chebli Mohamed

How to change the background color with Sprite Kit


I'm trying to make a game with Sprite Kit in Swift but I have a little problem with the background color.

I started a new project on Xcode and selected the "game" presets and Sprite Kit. So I have the starter project with a grey background with "Hello World" in white and spaceships that appear when I press on the screen.

So I removed all the code that I don't care about but when I launch the game, I still have the grey background, even if I try to change it in the GameScene.swift file.

Here is my files :

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    return true
  }

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  }

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  }

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  }

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  }

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  }

}

GameScene.swift

import SpriteKit

class GameScene: SKScene
{
  override func didMoveToView(view: SKView)
  {
    self.backgroundColor = SKColor.whiteColor()
  }

  override func update(currentTime: CFTimeInterval)
  {
    /* Called before each frame is rendered */
  }
}

GameViwController.swift

import UIKit
import SpriteKit


class GameViewController: UIViewController
{

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

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

So do you know how n I set the background in white ? Thank's !



via Chebli Mohamed

dyld: Library not loaded: @rpath/SwiftyJSON.framework/SwiftyJSON


I've been using the simulator to test my app. Today I decided to test it using other devices in the simulator and to my surprise it crashes on startup on some devices, on others it works perfectly

My app builds an runs on :

  • iPad Air
  • resizable iPad
  • iPhone 5S
  • iPhone 6
  • iPhone 6plus
  • resizable iPhone

My App crashes on:

  • iPad 2
  • iPad Retina
  • iPhone 4S
  • iPhone 5

The Error I'm Getting is :

dyld: Library not loaded: @rpath/SwiftyJSON.framework/SwiftyJSON

Referenced from: /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Demo Mobile
Reason: no suitable image found.
(lldb) 

Sometimes I even get more information :

Referenced from: /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Demo Mobile
Reason: no suitable image found.  Did find:
/Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo http://ift.tt/1Hq3QnT: mach-o, but wrong architecture
/Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo http://ift.tt/1Hq3QnT: mach-o, but wrong architecture
/Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo http://ift.tt/1Hq3QnT: mach-o, but wrong architecture
(lldb) 

I installed SwiftyJson via Cocoapods. My Podfile contains

platform :ios, '8.0'
use_frameworks!

pod 'SQLite.swift', git: 'http://ift.tt/1Shp2s8'

target 'thinx Mobile' do
    pod 'SwiftyJSON', '~> 2.2.1'
end

I tried :



via Chebli Mohamed

Using Swift Argo framework : Could not find an overload for '<*>'


I am using Argo with Runes and Box framework , i have followed the Carthage way of adding frameworks. Here is my Model Class for Cities

import Argo
import Runes

struct Cities {

let cityName: String
let cityState: String

 }

extension Cities: Decodable {
static func create(cityName: String)(cityState: String!) -> Cities {
    return Cities(cityName: cityName, cityState: cityState)
}

static func decode(j: JSON) -> Decoded<Cities>
{
    return Cities.create <*> j <| "cityName" <*> j <| "cityState"

}
}

I get the following error : Could not find an overload for '<*>' that accepts the supplied arguments at return Cities.create <*> j <| "cityName" <*> j <| "cityState"

How can i fix this issue?

sample json :

{"cityName":"Panaji","cityState":"Goa"}



via Chebli Mohamed

Calling facility from skype,tango etc


Currently I am working on a Calling App. I have completed simple calling facility in iphone and get back to app after call ended but now client wants a new feature as android that if Skype,tango,truecaller etc. calling applications are installed,then before making call, it ask to call via skype, tango, truecaller. means give a table of all installed apps which have calling facility,Is it possible. I tried a lot but did not get any solution. Thanks In Advance.



via Chebli Mohamed

Get assets-library video and send it - iOS


I am working on video recording and export with compression, I've got the url in the assets-library like : assets-library://asset.MOB?id=4....&ext=MOV how can i have control over the file for example and share it or send it?

here is my code :

- (IBAction)touchUpInsideButtonRecordVideo:(id)sender {
    if ([UIImagePickerController
         isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.mediaTypes = @[(id)kUTTypeMovie];
        [self presentViewController:picker animated:NO completion:nil];
    }
}

- (IBAction)touchUpInsideButtonCompressVideo:(id)sender {

    NSURL *urlAssertIn = [NSURL URLWithString:textFieldUrl.text];

    NSURL *urlOutTemporal = [self getAbsolutePathForTemporalFile];


    if(![self removeFileFromURL:urlOutTemporal]){
        NSLog(@"Fail removete temporal file");
        return;
    }

    AVURLAsset* videoAsset = [[AVURLAsset alloc] initWithURL:urlAssertIn options:nil];
    AVAssetExportSession* exportSession = [[AVAssetExportSession alloc] initWithAsset:videoAsset presetName:AVAssetExportPresetMediumQuality];
    exportSession.outputURL = urlOutTemporal;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;

    __weak typeof (self) weakSelf = self;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (AVAssetExportSessionStatusCompleted == exportSession.status) {
            [weakSelf replaceAsset:urlOutTemporal urlAssertReplace:urlAssertIn];
        } else {
            NSLog(@"Error Export Session: %@", [exportSession error]);
        }
    }];

    NSLog(@"I am here 1");

}

-(void) replaceAsset:(NSURL* )urlInTemporal urlAssertReplace:(NSURL*) urlAssertReplace {
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    __weak typeof (self) weakSelf = self;
    [assetslibrary assetForURL:urlAssertReplace resultBlock:^(ALAsset *asset) {
        if([asset isEditable]) {
            [weakSelf overrideAssert:asset urlInTemporal:urlInTemporal];
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"Error read asset: %@", error);
    }];

    NSLog(@"I am here 2");

}

-(void) overrideAssert:(ALAsset*) asset  urlInTemporal:(NSURL* )urlInTemporal{
    __weak typeof (self) weakSelf = self;
    [asset writeModifiedVideoAtPathToSavedPhotosAlbum:urlInTemporal completionBlock:^(NSURL *assetURL, NSError *error) {
        if(!error) {
            [weakSelf setNewVideoURL:assetURL];
            [weakSelf getSizeOfFile:assetURL];
        }
    }];
    NSLog(@"I am here 3");

}

#pragma mark compression

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
                                   outputURL:(NSURL*)outputURL
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: urlAsset presetName:AVAssetExportPresetHighestQuality];
    session.outputURL = outputURL;
    session.outputFileType = AVFileTypeMPEG4;
    [session exportAsynchronouslyWithCompletionHandler:^(void)
     {
         handler(session);

     }];
    NSLog(@"I am here 4");

}

#pragma mark delegate UIImagePickerController

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    NSURL *recordedVideoURL = [info objectForKey:UIImagePickerControllerMediaURL];

    __weak typeof(self) weakSelf = self;
    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:recordedVideoURL]) {
        [library writeVideoAtPathToSavedPhotosAlbum:recordedVideoURL completionBlock:^(NSURL *assetURL, NSError *error){
            if(!error) {
                [weakSelf setNewVideoURL:assetURL];
                [weakSelf getSizeOfFile:assetURL];
            }

        }];
    }
    NSLog(@"I am here 5");

    [picker dismissViewControllerAnimated:NO completion:nil];
}

#pragma mark update view controllers info

-(void) setNewVideoURL:(NSURL*) url {
    [textFieldUrl setText:[url absoluteString]];
}

-(void) setSizeOfOrigilaFile:(long) size {
    [labelSizeFile setText:[NSString stringWithFormat:@"%ld kb",size]];
}

-(void) getSizeOfFile:(NSURL*) url {
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:url resultBlock:^(ALAsset *asset) {
        [self setSizeOfOrigilaFile:[asset defaultRepresentation].size];
    } failureBlock:^(NSError *error) {
        NSLog(@"Error read asset: %@", error);
    }];
}

-(NSURL*)getAbsolutePathForTemporalFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths firstObject];
    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"temporal"];
    NSURL* temporalVideoURL = [NSURL fileURLWithPath:filePath];
    NSLog(@"I am here 6");

    return [temporalVideoURL URLByAppendingPathExtension:@"MOV"];

}


-(BOOL)removeFileFromURL:(NSURL*) urlFile {
    [[NSFileManager defaultManager] removeItemAtURL:urlFile error:nil];
    return true;
}

let say i have a method to share :

    - (IBAction)shareVideo:(id)sender {


}



via Chebli Mohamed

iOS Error when sending email or sms


I'm trying to send sms and email from an iOS app, but I encounter some problems.

I took the code from a tutorial, for example the sms code :

func sendMessage() {
    let prefs = NSUserDefaults.standardUserDefaults()
    var message = MFMessageComposeViewController()

    // Contacts
    var phoneNumbers = [String]()
    var phoneNumberNb: Int = prefs.objectForKey("phonenumberssaved")!.count
    for(var i = 0; i < phoneNumberNb; i++) {
        phoneNumbers.append(prefs.objectForKey("phonenumberssaved")!.objectAtIndex(i) as! String)
    }

    println(phoneNumbers)

    message.recipients = phoneNumbers
    message.body = self.messageText
    message.messageComposeDelegate = self

    self.presentViewController(message, animated: false, completion: nil)
} 

and I printed my datas (they seems to be ok), but when I try to send it, the app crash with a

'fatal error: unexpectedly found nil while unwrapping an Optional value' and it show me a strange file with a line highlighted : '0x4b5164 <+64>: trap'...



via Chebli Mohamed

Radio buttons get unselected while scrolling UITableView


I have two radio buttons on UITableView Cell.I am able to select one of them while scrolling UITableView down but when I scroll tableview up all radio buttons get unselected. After scrolling also I want to keep them selected but I am not able to do that....So please anyone having solution help me. Thank you

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];

    }

    leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtnclick.tag=999;
    [leftBtnclick setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    [leftBtnclick setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];

    if (screenHeight == 667)
    {
        [leftBtnclick setFrame:CGRectMake(50, 59, 30, 30)];
     }
    else if(screenHeight == 480)
    {
        [leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];

    }

    [leftBtnclick addTarget:self action:@selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.leftOptBtn addTarget:self action:@selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:leftBtnclick];

    rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtnclick.tag=1000;
    [rightBtnclick setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    [rightBtnclick setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];

    if (screenHeight == 667)
    {
       [rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
    }
    else if(screenHeight == 480)
    {
        [leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];

    }

    [rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
    [rightBtnclick addTarget:self action:@selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.rightOptBtn addTarget:self action:@selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:rightBtnclick];

    cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
    cell.questionLbl.text = [questionArray objectAtIndex:indexPath.row];
    [cell.leftOptBtn setTitle:[leftOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    [cell.rightOptBtn setTitle:[rightOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    return cell;
}

-(void)leftTickBtnClicked:(id)sender
{
    UIButton *leftTickBtn=(UIButton *)sender;
    leftTickBtn.selected=!leftTickBtn.selected;
    for(UIView *vw in [[sender superview]subviews])
    {
        if([vw isKindOfClass:[UIButton class]] && vw.tag==1000)
        {
            UIButton *rightTickBtn=(UIButton *)vw;

            if(leftTickBtn.selected)
            {
                rightTickBtn.selected=NO;
            }
            else
            {
                rightTickBtn.selected=YES;
            }

        }
    }

}

-(void)rightTickBtnClicked:(id)sender
{

    UIButton *rightTickBtn=(UIButton *)sender;
    rightTickBtn.selected=!rightTickBtn.selected;


    for(UIView *vw in [[sender superview]subviews])
    {
        if([vw isKindOfClass:[UIButton class]] && vw.tag==999)
        {
            UIButton *leftTickBtn=(UIButton *)vw;

            if(rightTickBtn.selected)
            {
                leftTickBtn.selected=NO;
            }
            else
            {
                leftTickBtn.selected=YES;
            }

        }
    }


}



via Chebli Mohamed

iOS - How to handle large amount of data from webservice


i am getting large amount of data from web service. If the amount of records it return is more than 1500 or 2000 the memory overflows and the app crashes. I don't need to save the data locally, just have to present the data to the user. How can i manage it not to crash and display whole of the data?



via Chebli Mohamed

How to implement Card view animation in iOS? [on hold]


I want to create a card animation like this. I have found one tutorial but it is in swift. I need one in objective-c. Anybody know any tutorial or sample code in objective-c? enter image description here

Please help me. thanks



via Chebli Mohamed

AddressBook not working in iOS9


Recently I have downloaded Xcode beta4 for giving support to iOS 9 in myApp.Now the address book is not working its show blank screen when I select a contact, with following logs.

plugin com.apple.MobileAddressBook.ContactsViewService interrupted plugin com.apple.MobileAddressBook.ContactsViewService invalidated

I have implemented all major delegate of ABPeoplePicker and put break points its not going in any of them.

Thanks in advance.



via Chebli Mohamed

How to track down which operation is low down the launching process?


It takes a long duration of time for my App to be launched. How can I track down which operation causes this trouble?



via Chebli Mohamed

One provisioning profile more than one team


I have been working with one team under apple developers program, using lot of provisioning profile when developing apple applications.

For some reason we needed to create another team but I would like to have both teams to share all the provisioning profiles.

Do you think it is possible?

I tried to download one provisioning profile and upload to the new team with no success :(

Thanks!!



via Chebli Mohamed

Wordpress on iPad, logo position issue


I'm developing this site: esident.logotypefactory.com Everything is ok on desktops, phones. But when it comes to iPads the logo duplicates or something is wrong...

So try this:

1) Go to esident.logotypefactory.com on your iPad 2) Swipe to the left so the screen goes to the right, you will see the second logotype.

Why does it do like that? What am I doing wrong?

What I want:

1) Have a logo always on the top left side. 2) When you click on the menu, have the logo also there on same place.

What I think:

That the second logo is the logo that should be viewable when you click on the menu. As when you click on the menu, you can't "swipe" to see the second logo.

Please help me guys.

<div class="fusion-header"><div class="fusion-row"><div class="fusion-logo" data-margin-top="65px" data-margin-bottom="31px" data-margin-left="0px" data-margin-right="0px"> <a href="http://ift.tt/1M988Ig"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" class="fusion-logo-1x fusion-standard-logo"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" style="width:221px; max-height: 51px; height: auto;" class="fusion-standard-logo fusion-logo-2x"> <img src="http://ift.tt/1M988Ii" alt="Esident" class="fusion-logo-1x fusion-mobile-logo-1x"> <img src="http://ift.tt/1ImH3v2" alt="Esident" style="max-width:195px; max-height: 47px; height: auto;" class="fusion-logo-2x fusion-mobile-logo-2x"> </a></div><div class="fusion-mobile-menu-icons"><a href="#" class="fusion-icon fusion-icon-bars"></a></div><div class="fusion-mobile-nav-holder"></div></div></div>

.fusion-header {



  padding-left: 30px;



  padding-right: 30px;



  -webkit-backface-visibility: hidden;



  backface-visibility: hidden;



}



.fusion-header-v2 .fusion-header,



.fusion-header-v3 .fusion-header,



.fusion-header-v4 .fusion-header,



.fusion-header-v5 .fusion-header {



  border-bottom: 1px solid transparent;



}



.fusion-logo {



  float: left;



  zoom: 1;



}



.fusion-logo:before,



.fusion-logo:after {



  content: " ";



  display: table;



}



.fusion-logo:after {



  clear: both;



}



.fusion-logo a {



  display: block;



}



.fusion-logo img {



  width: auto;



}



.fusion-logo-2x {



  display: none;



}



.fusion-mobile-logo-1x,



.fusion-mobile-logo-2x {



  display: none;



}



@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi), only screen and (min-resolution: 1.5dppx) {



  .fusion-standard-logo.fusion-logo-1x {



    display: none;



  }



  .fusion-standard-logo.fusion-logo-2x {



    display: inline-block;



  }



}



.fusion-secondary-header {



  min-height: 43px;



  border-bottom: 1px solid transparent;



}



.fusion-secondary-header .fusion-alignleft {



  float: left;



  margin-right: 0;



}



.fusion-secondary-header .fusion-alignright {



  float: right;



  margin-left: 0;



}



.fusion-header-v2 .fusion-secondary-header {



  border-top: 3px solid transparent;



}



.fusion-secondary-header .fusion-mobile-nav-holder {



  width: 80%;



  margin: 0 auto;



}



.fusion-header-separator {



  padding: 0 6px;



}



.fusion-contact-info {



  line-height: 43px;



}



.fusion-header-v4 .fusion-header {



  padding-top: 30px;



  padding-bottom: 30px;



}



.fusion-header-v4 .fusion-logo {



  width: 100%;



}



.fusion-header-v4 .fusion-logo a {



  float: left;



}



.fusion-header-v4 .searchform {



  float: right;



  margin-left: 15px;



}



.fusion-header-v4 .search-table {



  width: 286px;



}



.fusion-header-tagline {



  float: right;



  margin: 0;



  padding: 0;



  line-height: 32px;



  font-family: 'MuseoSlab500Regular', Arial, Helvetica, sans-serif;



  font-weight: normal;



}



.fusion-header-banner {



  float: right;



}



.fusion-logo .fusion-header-banner a {



  float: none;



}


via Chebli Mohamed

AFNetworking caching using ETag


I have problem implementing caching using AFNetworking and ETag values. My server returns Cache-Control and ETag headers values for every request. But if I make a second request for the same resource AFNetworking won't add ETag. Should I manually save etag for each response I got and append it to next requests?

In app delegate I have set cache object:

 NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
 [NSURLCache setSharedURLCache:URLCache];

Also, I'm using default cache policy of AFHTTPRequestSerializer.

Any ideas what is the problem? Maybe I don't understand the idea of http caching. As far as I know it should be transparent, and all I have to do is to attach ETag and Cache-Control headers for every response.

EDIT:

The headers of response looks like this:

"Cache-Control" = "max-age=3600";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 05 Aug 2015 07:52:33 GMT";
Etag = "W/f6c8a0f47deb7db0eeea3069061de9ab";
Expires = "Wed, 05 Aug 2015 08:52:30 GMT";
"Last-Modified" = "Wed, 05 Aug 2015 08:52:30 GMT";
Server = "cloudflare-nginx";
Vary = "Accept-Encoding";
"cf-ray" = "2110ec564bde0afc-WAW";
"x-cache-id" = "api_3447fddb8680ed5d082ae871e95214dc";
"x-powered-by" = "PHP/5.5.19";
"x-whom" = "www-stage02-b"



via Chebli Mohamed

AppCode no product for target


I am trying to run Swift iOS app in iPad simulator in AppCode. App is successfully built, but there is an error

Error running ios-app: No product for target 'ios-app'

I am quite green in iOS development and I am trying to switch from XCode to AppCode since I am more familiar with it.

I am using latest AppCode (3.1.7), everything works great in XCode.

Thanks for responses :)



via Chebli Mohamed

iOS - Delete / Update presented local notification


In my app I use Obj-C and present a local notification on push. When I get a new push I would like to edit the text in the notification or delete so I can present an updated one. I have tried to save the notification in the user defaults, retrieving it and using cancelLocalNotification function but it doesn't work.

Thanks in advanced for any help



via Chebli Mohamed

Slide Side Out Menu ExpandableTable Profile Img


I was trying to create a Slide side out menu using the SWRevealViewController but I could not do the expandableTable and the profile with image + Hello,Name...

what i need

And all I could do was:

what i already done

basically is the expandableTableView and the profile,any examples of how to do this?



via Chebli Mohamed

Bridging header error -- "xxx-Bridging-Header.h"file does not exit in SWIFT


I got an solution for bridging-header.h file does not exit. Just want to share, hope it may help others too.

Follow below steps:-

  1. First of all delete all header file if you have implemented any.
  2. Add new header file from the ios templet. Hope you know how to add any new file, just follow in same manner.
  3. Now go to the buid setting and there search for objective-c bridging header, simply put the header file name with .h extension too.

please see the image how to add the file name in objective-c Bridging Header

enter image description here



via Chebli Mohamed

Swift : Collection View : Resize cell at the middle


I am using collection view in Storyboard. I want to resize the middle cell to be larger. It should be similar to this image.

enter image description here



via Chebli Mohamed

Turn off audio playback of AVPlayer?


I have a AVPlayer with AVPlayerItem. What i want is to turn off the audio playback off AVPlayer. I want play just video.

Can someone help me? Thank you!

    self.avPlayerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
    [self.avPlayer play];
    self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;


    self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidPlayToEndTime:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.avPlayerItem];


    CGRect screenRect = [[UIScreen mainScreen] bounds];

    self.avPlayerLayer.frame = CGRectMake(0, 0, screenRect.size.width , screenRect.size.height );
    [self.view.layer insertSublayer:self.avPlayerLayer atIndex:0];



via Chebli Mohamed

Apple pay for sout africa market


I want to implement Apple Pay in one of my application. However while reading I got post that it is supported only for UK and US and not for south africa. If I upload a build having apple pay functionality. will it work for south africa? And also are there chances of rejection of build?



via Chebli Mohamed

Integrating parse in Xcode7 beta


I'm trying to integrate parse in my swift project via xcode7 beta,I have added Parse frame work and also added all other dependencies, but when I try to import Parse in AppDelegate Xcode is telling "No such module 'parse'",I'm sure that I have linked all the dependency and Parse framework in BuildPhases and as I'm using pure swift there is no need of bridging header. Any help will be appreciated...

enter image description here

Unable import Parse



via Chebli Mohamed

Using sqlite3 in swift framework (step by step) XCode 6.4


The following steps were successfully done:

  1. add libsqlite3.dylib in (general/Frameworks and libraries)
  2. Project explorer: create under root a new group called "module"
  3. in module group create a new file module.map
  4. edit the module.map as following

module sqlite3 [system] { header "/Applications/http://ift.tt/1DtlgVE"

link "sqlite3"

export *

}

Using a terminal check the above sqlite3.h path to be sure that is there and adapt it if you have new/older OS release.

  1. add module.map to Build settings -> Swift compiler -> Search paths -> Import paths

  2. create your swift class and #import sqlite3

Deepening on XCode version you might encounter the following issue

"opening import file for module 'Swift': Not a directory"

Make sure the module.map is well specified in settings.



via Chebli Mohamed

how to set button background image size


I want to create this button in my application. I have added a button to my view in storyboard. Set it's width and height constraints to 60px.

Then in code I've added corner radius and UIImage to background but the image filled the whole button background. The image is 22x22px. I want it to be centered in button like on my screenshot.

var pencilImage = UIImage(named: "pencil")!
pencilBtn.setBackgroundImage(pencilImage, forState: UIControlState.Normal)
pencilBtn.layer.cornerRadius = pencilBtn.frame.size.height / 2
pencilBtn.clipsToBounds = true

What should I code to solve this?



via Chebli Mohamed

switch tab bar before navigation to another viewcontroller


I am making an iOS app where I have Tab bar + Side Menu.

Tab bar have 5 items and side menu have around 12 menus.

All side menu functionalities are from Tab 1 & side menu is accessible across all views in tab bar.

That means if I am on Tab 2, even I can access side menu. When I click on side menu item from Tab 1, I will go to Tab 1 and then navigation will occur.

What I want to do is let's say if I click on Complains menu from side menu, I want to go to ComplainsViewController.

Code I used is as below.

// go to first tab
self.tabBarController.selectedIndex = 0;
// now navigate
ComplainsViewController *sViewCon = [self.storyboard instantiateViewControllerWithIdentifier:@"Complains"];
CATransition *transition = [CATransition animation];
transition.duration = 0.5;
transition.type = kCATransitionFade;
[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:sViewCon animated:NO];

I have two scenario.

Scenario 1 (Correct)

I am on Tab 1 and click on Complains from side menu. When I click, I go successfully to ComplainsViewController using above code.

Scenario 2 (In-Correct)

I am on Tab 2 and click on Complains from side menu. When I click, I go successfully to Tab 1, but I don't navigate to ComplainsViewController. When I click back to Tab 2, I see ComplainsViewController open in Tab 2.

Any idea how to switch first to Tab and then navigate to another viewcontroller?


Edit 1

Below is the basic structure I have.

enter image description here



via Chebli Mohamed

Create a list with text, image, button in storyboard


I would like to have a view on my storyboard, with a part of text, then an image, then another part of text and finally a button. Text and image has to be variable and could be changed. Most of the time, text will be very long.

I m looking for the best way to perform it.

Should i use a UIScrollView and input a label, an image, a label and a button ?

Or just a label, an image, a label and a button ?

Any help will be appreciated.



via Chebli Mohamed

iOS integration with Unity 3D 5.1.1


I'm trying to create an application with Unity and iOS. I have created iOS code from unity and I linked it with unity code.It build successfully and when it running on the iPad gives this error and app went to crash.(black screen). Need a solution from experts. Thank you.

This is the error log I got.

-> applicationDidBecomeActive() Requesting Resolution: 1152x1536 Renderer: PowerVR SGX 543 Vendor: Imagination Technologies Version: OpenGL ES 2.0 IMGSGX543-97 GLES: 2 GL_OES_depth_texture GL_OES_depth24 GL_OES_element_index_uint GL_OES_fbo_render_mipmap GL_OES_mapbuffer GL_OES_packed_depth_stencil GL_OES_rgb8_rgba8 GL_OES_standard_derivatives GL_OES_texture_float GL_OES_texture_half_float GL_OES_texture_half_float_linear GL_OES_vertex_array_object GL_EXT_blend_minmax GL_EXT_color_buffer_half_float GL_EXT_debug_label GL_EXT_debug_marker GL_EXT_discard_framebuffer GL_EXT_draw_instanced GL_EXT_instanced_arrays GL_EXT_map_buffer_range GL_EXT_occlusion_query_boolean GL_EXT_pvrtc_sRGB GL_EXT_read_format_bgra GL_EXT_separate_shader_objects GL_EXT_shader_framebuffer_fetch GL_EXT_shader_texture_lod GL_EXT_shadow_samplers GL_EXT_sRGB GL_EXT_texture_filter_anisotropic GL_EXT_texture_rg GL_EXT_texture_storage GL_APPLE_copy_texture_levels GL_APPLE_framebuffer_multisample GL_APPLE_rgb_422 GL_APPLE_sync GL_APPLE_texture_format_BGRA8888 GL_APPLE_texture_max_level GL_IMG_read_format GL_IMG_texture_compression_pvrtc OPENGL LOG: Creating OpenGL ES 2.0 graphics device



via Chebli Mohamed

iOS8 change pop over trait collection


I'm deploying an application on both iphone and ipad (iOS7 and iOS8).
I'm using storyboard with size classes, basically I have a base size classes Any-Any that fits iPad layout and a Compact-Regular that fits all iphone models.
SOme view controllers in the iPAd version are presented with a custom slide in/out segue, others i popovers.
While it works perfectly on iOS7 ipad (since xcode build different storyboards) on iOS8 I have the problem that what is shown in the popover picks the iphone interface.
I present it in the usual way:

    weakSelf.myPop = [[UIPopoverController alloc ] initWithContentViewController:commentVC];
 [weakSelf.myPop presentPopoverFromRect:[[(AFPostTimelineTableViewCell*)cell commentButton] frame] inView:cell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
  weakSelf.myPop.delegate = weakSelf;

Checking the code I've seen that the presented view controller has a UITrait collection of C-R.
Is there a way to make it pick the R-R?



via Chebli Mohamed

Inconsistent Results with GTLQueryDrive - Google Api "no result or error in response"


I am running queries against Google Drive for photos , sometimes they work sometimes not, sometimes half work.

Occasionally I get an assertion error with a 200 response codes but no data

GTLService.m parseObjectFromDataOfFetcher

GTL_DEBUG_ASSERT(errorJSON != nil, @"no result or error in response:\n%@",

I am using Cocapods

  • Using Google-API-Client (1.0.422)
  • Using gtm-http-fetcher (1.0.141)
  • Using gtm-oauth2 (1.0.126)

These are my scopes

NSString *scope = [GTMOAuth2Authentication scopeWithStrings:kGTLAuthScopeDriveReadonly, @"http://ift.tt/1KQ1GFO", nil];

When I run the same query using http://ift.tt/1KPYqHC It works fine

[GTMHTTPFetcher setLoggingEnabled:YES];

I have tried using logging but I cannot see any errors. I notice that GTL uses POST and the WebInterface GET is this significant ?

Here is an example. I have 9 Photos in my Drive my query only returns 3. Two of the photos it finds are in the base directory and one in the Google Photos directory. I the rerun the query and the second time it may return all 9 photos. That log is included at the very bottom of the post

Here is my Log

drive.files.list

2015-08-05 09:24:25 +0000
Request: POST http://ift.tt/1KQ1GFQ
Request headers:
  Accept: application/json-rpc
  Authorization: Bearer _snip_
  Cache-Control: no-cache
  Content-Type: application/json-rpc; charset=utf-8
  User-Agent: com.hyperlync.homelync/1.0 google-api-objc-client/2.0 iPhone/8.4 hw/iPhone5_4 (gzip)

Request body: (293 bytes)
{
  "method" : "drive.files.list",
  "id" : "gtl_9",
  "jsonrpc" : "2.0",
  "params" : {
    "q" : "(trashed = false and mimeType contains 'image')",
    "maxResults" : 250,
    "fields" : "items(fileSize,thumbnailLink,downloadUrl,originalFilename,iconLink,mimeType,modifiedDate,fileExtension,title),nextPageToken"
  },
  "apiVersion" : "v2"
}

Response: status 200
Response headers:
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Content-Encoding: gzip
  Content-Length: 803
  Content-Type: application/json; charset=UTF-8
  Date: Wed, 05 Aug 2015 09:24:24 GMT
  Etag: "9Atp-NBKQmHtE7w2vMGY_7-2FUk/-b328o5iuA8H2rPWmZLSIFewPNY"
  Expires: Fri, 01 Jan 1990 00:00:00 GMT
  Pragma: no-cache
  Server: GSE
  Vary: Origin, X-Origin
  alternate-protocol: 443:quic,p=1
  x-content-type-options: nosniff
  x-frame-options: SAMEORIGIN
  x-xss-protection: 1; mode=block

Response body: (2147 bytes)
{
  "id" : "gtl_9",
  "result" : {
    "items" : [
      {
        "fileExtension" : "jpg",
        "originalFilename" : "1.jpg",
        "modifiedDate" : "2015-07-29T12:46:05.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "94524",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh5.googleusercontent.com\/itG6alVmJ32qoCpyetQdocb9pag47QClUUtmOJZOsA6Xh-fSwIACGcy3pfzAYxin5WbZ5J5rVCsl=s220",
        "downloadUrl" : "https:\/\/doc-0c-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/esoca7vo8mdhvrc9e1rs6ackb30l651r\/1438761600000\/00092883636123010676\/00092883636123010676\/1jeOnV_4wImVPqWpbyfl70x0XFUJLymtxaw?e=download&gd=true",
        "title" : "1.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "yael.jpg",
        "modifiedDate" : "2015-07-28T12:29:51.971Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "26576",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh6.googleusercontent.com\/NpNqziF-AAFqCC56yxO6Tjfe5Wb7Ve3lBMtCDKm3lJdtF0Z0ApIqPdbmni-kbSPNrdzcmQ=s220",
        "downloadUrl" : "https:\/\/doc-0s-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/6ccm5ltlo0j76rphsach7hktd51nrakh\/1438761600000\/00092883636123010676\/00092883636123010676\/0B-X-qhbL0RO4N0VUTVNORUtESnM?e=download&gd=true",
        "title" : "yael.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "11638561_1442659529371446_1406073403_o.jpg",
        "modifiedDate" : "2015-07-28T12:29:50.638Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "133493",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh4.googleusercontent.com\/C4BN0mhBefHgscOrqjsYUY3HEBb3gSB6MUAsgweWeYNKyUFgvgGXDcGCQJ-QT-dV_QDqmw=s220",
        "downloadUrl" : "https:\/\/doc-0s-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/galmab7earuanos65umbu7ecq2d3cbk6\/1438761600000\/00092883636123010676\/00092883636123010676\/0B-X-qhbL0RO4Z3hNZy1sNC1wNm8?e=download&gd=true",
        "title" : "11638561_1442659529371446_1406073403_o.jpg"
      }
    ]
  }
}
-----------------------------------------------------------

Now for comparison here is the same query using the Web interface

GET http://ift.tt/1KPYqHE}
Response

200 OK
- SHOW HEADERS -
{
 "items": [
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYoQ7",
   "title": "3.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:12.000Z",
   "downloadUrl": "http://ift.tt/1KQ1Flq",
   "originalFilename": "3.jpg",
   "fileExtension": "jpg",
   "fileSize": "263619"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYoQ9",
   "title": "6.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:07.000Z",
   "downloadUrl": "http://ift.tt/1KQ1GFS",
   "originalFilename": "6.jpg",
   "fileExtension": "jpg",
   "fileSize": "329242"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYqHK",
   "title": "4.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:07.000Z",
   "downloadUrl": "http://ift.tt/1KQ1Fls",
   "originalFilename": "4.jpg",
   "fileExtension": "jpg",
   "fileSize": "224973"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYqHO",
   "title": "5.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:06.000Z",
   "downloadUrl": "http://ift.tt/1KQ1FBG",
   "originalFilename": "5.jpg",
   "fileExtension": "jpg",
   "fileSize": "313036"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYqHQ",
   "title": "1.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:05.000Z",
   "downloadUrl": "http://ift.tt/1KQ1FBI",
   "originalFilename": "1.jpg",
   "fileExtension": "jpg",
   "fileSize": "94524"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYoQh",
   "title": "2.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:46:05.000Z",
   "downloadUrl": "http://ift.tt/1KQ1GFY",
   "originalFilename": "2.jpg",
   "fileExtension": "jpg",
   "fileSize": "621450"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYqHU",
   "title": "IMG_0561.JPG",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-29T12:43:42.000Z",
   "downloadUrl": "http://ift.tt/1KQ1FBQ",
   "originalFilename": "IMG_0561.JPG",
   "fileExtension": "jpg",
   "fileSize": "1091283"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYqY8",
   "title": "yael.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-28T12:29:51.971Z",
   "downloadUrl": "http://ift.tt/1KQ1FBS",
   "originalFilename": "yael.jpg",
   "fileExtension": "jpg",
   "fileSize": "26576"
  },
  {
   "iconLink": "http://ift.tt/QFJSBi",
   "thumbnailLink": "http://ift.tt/1KPYp6D",
   "title": "11638561_1442659529371446_1406073403_o.jpg",
   "mimeType": "image/jpeg",
   "modifiedDate": "2015-07-28T12:29:50.638Z",
   "downloadUrl": "http://ift.tt/1KQ1GWg",
   "originalFilename": "11638561_1442659529371446_1406073403_o.jpg",
   "fileExtension": "jpg",
   "fileSize": "133493"
  }
 ]
}

Log when I run another time it gets all 9 photos

drive.files.list

2015-08-05 09:51:39 +0000
Request: POST http://ift.tt/1KQ1GFQ
Request headers:
  Accept: application/json-rpc
  Authorization: Bearer _snip_
  Cache-Control: no-cache
  Content-Type: application/json-rpc; charset=utf-8
  User-Agent: com.hyperlync.homelync/1.0 google-api-objc-client/2.0 iPhone/8.4 hw/iPhone5_4 (gzip)

Request body: (293 bytes)
{
  "method" : "drive.files.list",
  "id" : "gtl_1",
  "jsonrpc" : "2.0",
  "params" : {
    "q" : "(trashed = false and mimeType contains 'image')",
    "maxResults" : 250,
    "fields" : "items(fileSize,thumbnailLink,downloadUrl,originalFilename,iconLink,mimeType,modifiedDate,fileExtension,title),nextPageToken"
  },
  "apiVersion" : "v2"
}

Response: status 200
Response headers:
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Content-Encoding: gzip
  Content-Length: 1648
  Content-Type: application/json; charset=UTF-8
  Date: Wed, 05 Aug 2015 09:51:39 GMT
  Etag: "9Atp-NBKQmHtE7w2vMGY_7-2FUk/xuqdPiWl-18ksn_DJ0LoyxtR7WI"
  Expires: Fri, 01 Jan 1990 00:00:00 GMT
  Pragma: no-cache
  Server: GSE
  Vary: Origin, X-Origin
  alternate-protocol: 443:quic,p=1
  x-content-type-options: nosniff
  x-frame-options: SAMEORIGIN
  x-xss-protection: 1; mode=block

Response body: (6248 bytes)
{
  "id" : "gtl_1",
  "result" : {
    "items" : [
      {
        "fileExtension" : "jpg",
        "originalFilename" : "3.jpg",
        "modifiedDate" : "2015-07-29T12:46:12.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "263619",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh3.googleusercontent.com\/F4G26Qp08vhZAB3PniZ4eTtoZuClAeMHKSF_AB1aLSp1YI3qwfuKKLkOriIAIbqa5AVlFwNvLT1C=s220",
        "downloadUrl" : "https:\/\/doc-08-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/p3u7qp6tpnj2vfhcbrtdhsuf5q6hrqka\/1438761600000\/00092883636123010676\/00092883636123010676\/13QefjrZBi4qwZ260isfSuhXUnriohjb00A?e=download&gd=true",
        "title" : "3.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "6.jpg",
        "modifiedDate" : "2015-07-29T12:46:07.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "329242",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh4.googleusercontent.com\/FrjC6BW73yHVpGyqeLG22lAixO6b9Z7kMh27yCmzmFmYpAywidxkan-jwf04CLm8l4hipJtmMRkV=s220",
        "downloadUrl" : "https:\/\/doc-0g-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/upti9c2dsp9acbpcfl4g497koqlj8sjh\/1438761600000\/00092883636123010676\/00092883636123010676\/1uM4b53TqUkvgVZ0HOnO3Jy1_zmnjG8btaw?e=download&gd=true",
        "title" : "6.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "4.jpg",
        "modifiedDate" : "2015-07-29T12:46:07.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "224973",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh6.googleusercontent.com\/kL5ROytrtaIHKO6iiQ_xwefDAFVUGgyyeewkYWcL1rudoTda4IGlUxAjpo877yw96PcDg6xh9HPA=s220",
        "downloadUrl" : "https:\/\/doc-10-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/punud1ktmfspfpd4smakfknjlh8mr3mc\/1438761600000\/00092883636123010676\/00092883636123010676\/1ijAydp5YbNEtNYhPb91B8VNid2BKQKZwdw?e=download&gd=true",
        "title" : "4.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "5.jpg",
        "modifiedDate" : "2015-07-29T12:46:06.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "313036",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh3.googleusercontent.com\/KJtZ4M3P66-3N5PrXKPeg9ArXUaxJydvAI-kbTDbfqfw0LGGgo6zYwc3OGzTh5G8u831fjc6VXx1=s220",
        "downloadUrl" : "https:\/\/doc-08-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/g0fb2jig1lhculeiud09bfupqvpei16r\/1438761600000\/00092883636123010676\/00092883636123010676\/1xsSkBgMa9dfzvaj5HvDkCiSei0cqWUoBeg?e=download&gd=true",
        "title" : "5.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "1.jpg",
        "modifiedDate" : "2015-07-29T12:46:05.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "94524",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh4.googleusercontent.com\/64BZkh33dOhSHGiIqpMhaccobQOy_4stoiZwulHAUx83K5d9bp9TQ0ERjyciZt0nMKmLjOEQBo4H=s220",
        "downloadUrl" : "https:\/\/doc-0c-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/esoca7vo8mdhvrc9e1rs6ackb30l651r\/1438761600000\/00092883636123010676\/00092883636123010676\/1jeOnV_4wImVPqWpbyfl70x0XFUJLymtxaw?e=download&gd=true",
        "title" : "1.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "2.jpg",
        "modifiedDate" : "2015-07-29T12:46:05.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "621450",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh6.googleusercontent.com\/KU4h1BLr-78AG0a6ssfDlMbuhBNHrvDF-uRdcs6jAJS77BqdlLP58uI6raG76DWFWz0gkr9NHBjZ=s220",
        "downloadUrl" : "https:\/\/doc-0k-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/ju8n7hgnr40qqvqg0h0ofpna6mnm95l1\/1438761600000\/00092883636123010676\/00092883636123010676\/1gEOweTVA7ULw3glonuY2U_4RJElL7ccrmw?e=download&gd=true",
        "title" : "2.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "IMG_0561.JPG",
        "modifiedDate" : "2015-07-29T12:43:42.000Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "1091283",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh5.googleusercontent.com\/jQxfzPNpn3SDTtJQJ0SefJ1AZ7NaMuBwTDF_y4UVrVhMQzXhOPA5QK2BWWq4OACa7l54MNFlBf0o=s220",
        "downloadUrl" : "https:\/\/doc-0c-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/celm0nk5fjm33gc73ofpsvl3n1am4mmk\/1438761600000\/00092883636123010676\/00092883636123010676\/1AV6pTqt8Sur4Q6QBqUmAloZXI-4kMCySPg?e=download&gd=true",
        "title" : "IMG_0561.JPG"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "yael.jpg",
        "modifiedDate" : "2015-07-28T12:29:51.971Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "26576",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh3.googleusercontent.com\/zTiw6fbEZL0ujzctWiGaRGa-tjwfGuWIW6R1W9FDTGrvAbY-qoERSK7blyTkTI7r4pDosw=s220",
        "downloadUrl" : "https:\/\/doc-0s-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/6ccm5ltlo0j76rphsach7hktd51nrakh\/1438761600000\/00092883636123010676\/00092883636123010676\/0B-X-qhbL0RO4N0VUTVNORUtESnM?e=download&gd=true",
        "title" : "yael.jpg"
      },
      {
        "fileExtension" : "jpg",
        "originalFilename" : "11638561_1442659529371446_1406073403_o.jpg",
        "modifiedDate" : "2015-07-28T12:29:50.638Z",
        "mimeType" : "image\/jpeg",
        "fileSize" : "133493",
        "iconLink" : "https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_image_list.png",
        "thumbnailLink" : "https:\/\/lh6.googleusercontent.com\/vR95FnE2KV_a-2huvmdMQsQMvnf6ZrenTC81v7652iJ5T2uC7v-YaDLK9K6ODnA8Alm1dw=s220",
        "downloadUrl" : "https:\/\/doc-0s-8s-docs.googleusercontent.com\/docs\/securesc\/6jbbjm36tl2vvbnepiqedkpbkuhg3r98\/galmab7earuanos65umbu7ecq2d3cbk6\/1438761600000\/00092883636123010676\/00092883636123010676\/0B-X-qhbL0RO4Z3hNZy1sNC1wNm8?e=download&gd=true",
        "title" : "11638561_1442659529371446_1406073403_o.jpg"
      }
    ]
  }
}
-----------------------------------------------------------



via Chebli Mohamed

samedi 25 avril 2015

Bug in C++ Segment Tree Implementation?


I implemented a segment tree that seemed to work when I tested it with small inputs, but produces wrong answer when I tried to solve a problem with it. I'm sure that the bug is in the segment tree, but I can't find it. Can someone find the bug in my implementation? Code is below.

class SegmentTree
{
public:
    int* st;
    int* a;
    int length;
    SegmentTree(int* arr, int n)
    {
        length = n;
        a = arr;
        int height = (int)(ceil(log2(n)));
        int maxSize = 2 * (1 << height) - 1;
        st = new int[maxSize];
        build(0, 0, length - 1);
    }
    int f(int a, int b) // change for different problems
    {
        return max(a, b);
    }
    void build(int node, int l, int r)
    {
    if (l == r)
        st[node] = a[l];
    else
    {
        int mid = (l + r) / 2;
        build(node * 2 + 1, l, mid);
        build(node * 2 + 2, mid + 1, r);
        st[node] = f(st[node * 2 + 1], st[node * 2 + 2]);
    }

    void update(int i, int v)
    {
        update(0, 0, length - 1, i, v); //if sum query last parameter should     be v - a[i], otherwise should be v
        a[i] = v;
    }
    void update(int node, int sl, int sr, int i, int v) 
    {
        if (i < sl || i > sr)
            return;
        st[node] = f(st[node], v);
        if (sl != sr)
        {
            int mid = (sl + sr) / 2;
            update(node * 2 + 1, sl, mid, i, v);
            update(node * 2 + 2, mid + 1, sr, i, v);
        }
    }

    int query(int ql, int qr)
    {
        return query(0, 0, length - 1, ql, qr);
    }
    int query(int node, int sl, int sr, int ql, int qr)
    {
        if (sl > qr || sr < ql)
            return -1;
        if (sl >= ql && sr <= qr)
            return st[node];
        int mid = (sl + sr) / 2;
        int a = query(node * 2 + 1, sl, mid, ql, qr);
        int b = query(node * 2 + 2, mid + 1, sr, ql, qr);
        if (a == -1)
            return b;
        if (b == -1)
            return a;
        return f(a, b);
    }
};

int main()
{
    int a[] = { 4, 1, 2, 0, 6 };
    SegmentTree st(a, 5);
    cout << st.query(0, 2) << endl;
}


Error when compiling/mexing imrender function with OS X in Matlab


I am trying to use a specific function in Oliver Woodford's imrender_v2.4.zip (http://ift.tt/1IWlmDh) in Matlab, specifically the vgg_qpbo function.

The related files are supposed to recognize that a mex-file does not exist and compile one.

However, after running startup.m and trying something like

>> vgg_qpbo(1,1,1)

I get

Warning: Missing MEX-file: vgg_qpbo. Will attempt to compile and run. 
 > In vgg_mexcompile_script at 25
  In vgg_qpbo at 84 
mex -O -I"/Users/.../imrender/vgg" "-Iqpbo/" "vgg_qpbo.cxx" "qpbo/QPBO.cpp" "qpbo/QPBO_maxflow.cpp" "qpbo/QPBO_extra.cpp" "qpbo/QPBO_postprocessing.cpp"
Building with 'Xcode Clang++'.
In file included from /Users/.../imrender/vgg/vgg_qpbo.cxx:11:
In file included from qpbo/QPBO.h:116:
qpbo/block.h:124:56: warning: conversion from string literal to 'char *' is deprecated [-Wc++11-compat-deprecated-writable-strings]
                            if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
                                                                               ^
qpbo/block.h:223:56: warning: conversion from string literal to 'char *' is deprecated [-Wc++11-compat-deprecated-writable-strings]
                    if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
                                                                        ^
2 warnings generated.

ERROR while compiling vgg_qpbo
Error using vgg_mexcompile_script (line 30)
Unable to compile vgg_qpbo.

Error in vgg_qpbo (line 84)
vgg_mexcompile_script; % Compilation happens in this script

I have been trying to figure out what is the problem. The main suspect is the Mac OS X (Yosemite 10.2) I am running, as it is compilable on a Linux version (do not know which, but I could find out if you think it is relevant) my supervisor used. It is not exclusive to my computer as we tried it on another mac with the exact same result.

I believe the warnings are ignorable as they are just warnings (I am not savvy in C++, but I gathered that it is a relatively new warning, but should not affect the compilation itself).

I have also tried figuring out where in the scripts the error occurs, but the mexing-part is definitely starting, and further than that I do not feel comfortable to go.

I have mexed other scripts on this computer before and I can run for example

>> mex -setup

without a hitch.

So does anyone know what the problem might be? And thank you for your time!

I am running Matlab R2014B by the way.


Bit field memory


If i declare something like this

struct S{
  unsigned int bit:4;
}

How is it working?

  1. I allocate 2 bytes in memory(size of structure(got this size from here http://ift.tt/1a6LHjs) but use only 4 bits of it, and other memory in that structure is wasted.
  2. I allocate only 4 bits, nothing more.

I'm very confused about this and can't find any info about this anywhere.


STL SET Iterator assignment no viable candidate


I have a C++ program using an STL Set with an iterator. The set and iterator are defined as:


 set<TokenTableEntry*, Comparator> _XCLITokenTable;

 set<TokenTableEntry*>::const_iterator it;

I have a routine called findToken (shown below), that has a statement: it = _XCLITokenTable.find(_TokenTableEntry);

Which is producing the error message:

"implicit std::_Tree std::less,std::allocator,0> >::const_iterator::operator=(const
std::_Tree,std::allocator,0> >::const_iterator &)" is not a viable candidate.

I have no idea what this message is telling me or how to correct it. Can anyone make a suggestion?

Thanks for any help.

John

int XCLITokenTable::findToken (string name,  TokenTableEntry *_TokenTableEntry) 
{

    int type;
    type = -1;

    string lookupName(name);

    std::transform(name.begin(), name.end(), name.begin(), ::tolower);

    _TokenTableEntry->name = lookupName;

    **it = _XCLITokenTable.find(_TokenTableEntry);**

    if (it != _XCLITokenTable.end())
    {
        if ((*it)->name == name)
        {
            type = (*it)->type;
            tokenCount++;
            *_TokenTableEntry = *(*it);
            return type;
        }

    }
    return type;
}


Can a forwarding reference be aliased with an alias template?


This is a continuation of my previous question:

Can an identity alias template be a forwarding reference?

It seems that the following code works in both Clang 3.7.0 (demo) and GCC 6.0.0 (demo):

template <class T>
using forwarding_reference = T&&;

template <class T>
void foo(forwarding_reference<T>) {}

int main()
{
  int i{};
  foo(i);
  foo(1);
}

Are the compilers right to substitute the alias template for a forwarding reference and this could be a fancy way of writing one?


C++ and Fortran interoperability


For my own entertainment I have decided to create a large scale physics engine. I have experience with Java and C++ but none with Fortran. My understanding of Fortran is that it is used in the scientific industry and is good for large calculations. I decided to use C++ for any gui, sound, user input, etc. that might be added while Fortran would handle the calculations. How easy is it to call Fortran methods from C++? I have googled the matter and haven't found much information. Despite not knowing Fortran I am determined to learn it no matter how strict the learning curve may be (assuming that I will get an appropriate performance increase). Is it practical to use Fortran in this way? Will I get a decent performance increase (for large calculations)? Is Fortran still used in the modern world or is it outdated?


Are array memory addresses always in the order of least to greatest?


When I'm making a procedure with pointer arithmetic and !=, such as

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n; 
    while (arr != end && arr != --end) 
    {
         swap(arr,end);
         ++arr;
    }
}

I always take a lot of caution because if I write my procedure wrong then in a corner case the first pointer might "jump over" the second one. But, if arrays are such that

&arr[0] < &arr[1] < ... < &arr[n]

for any array arr of length n-1, then can't I just do something like

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n;
    if (arr == end) break;
    --end;
    while (arr < end)
    {
        swap(arr,end);
        ++arr; --end;
    }
}

since it's more readable? Or is there a danger looming? Aren't memory addresses just integral types and thus comparable with < ?


I want to know how to perform input and output operations in C#


I want to know how to perform input and output operations in C#.I know C++ but I want to write a code in C. This is the basic code in C++ I want to write the same thing using C language.

    #include<iostream.h>
    #include<conio.h>
    void main()
    {
    clrscr();
    char name;
    cout<<"\n Enter name";
    cin>>name;
    cout<<"Hello!!"<<name<<": \t ";
    getch();
    }


CMake. Create coverage target


Sorry for such popular question. But I can't correspondingly apply answers from here to my environment.

I have api and tests to it. Both are subprojects to main "dummy" project. I stuck because I used CMake-anitpattern:

cmake_minimum_required (VERSION 2.8)
set(CMAKE_SKIP_RPATH FALSE)
add_subdirectory ( src )
add_subdirectory ( test )

add_custom_target(coverage
    COMMAND make
    COMMAND sh ${CMAKE_SOURCE_DIR}/do_coverage.sh
)

That COMMAND make is bad solution because I planning to build my project on Windows later (yep, I need put commands from sh-script in CMakeLists.txt for this purpose too).

So, how can I let CMake to build test project in automatic mode for doing coverage things (gcov, gcovr) even if after cmake I want to make coverage straightway? Thanks!


Passing MyClass defined in header as function argument to other file


I've spent around an hour and couldn't find anything helpful on the Web. The problem is that I've got some files like a.h, b.h, a.cpp, b.cpp and main.cpp. In a.h I've got declared a container with attributes defined by myself. I would like to pass this container as and argument to the function in b.h/b.cpp. What is the way of doing this?

a.h file

struct Container{
int size;
int* array
...};

b.cpp

void someFunction(Container container)
{...}

Thanks for any help.