COMPUTER SCIENCE, TECHNOLOGY, Uncategorized

iOS – Sharing file path between a share extension and iOS app

Here’s an app store accepted way to share file path between an extension and an app.

  1. Share extension
#import "ShareViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
//Macro to hide post dialog or not, if defined, will be hidden, comment during debugging
#define HIDE_POST_DIALOG

@interface ShareViewController ()

@end

@implementation ShareViewController

NSUInteger m_inputItemCount = 0; // Keeps track of the number of attachments we have opened asynchronously.
NSString * m_invokeArgs = NULL; // A string to be passed to your AIR app with information about the attachments.
NSString * APP_SHARE_GROUP = @"group.com.schemename.nameofyourshareappgroup";
const NSString * APP_SHARE_URL_SCHEME = @"schemename";
CGFloat m_oldAlpha = 1.0; // Keeps the original transparency of the Post dialog for when we want to hide it.

- (BOOL)isContentValid {
// Do validation of contentText and/or NSExtensionContext attachments here
return YES;
}

- ( void ) didSelectPost
{
#ifdef HIDE_POST_DIALOG
return;
#endif

[ self passSelectedItemsToApp ];
// Note: This call is expected to be made here. Ignore it. We'll tell the host we are done after we've invoked the app.
// [ self.extensionContext completeRequestReturningItems: @[] completionHandler: nil ];
}
- ( void ) addImagePathToArgumentList: ( NSString * ) imagePath
{
assert( NULL != imagePath );

// The list of arguments we will pass to the AIR app when we invoke it.
// It will be a comma-separated list of file paths: /path/to/image1.jpg,/path/to/image2.jpg
if ( NULL == m_invokeArgs )
{
m_invokeArgs = imagePath;
}
else
{
m_invokeArgs = [ NSString stringWithFormat: @"%@,%@", m_invokeArgs, imagePath ];
}
}

- ( NSString * ) saveImageToAppGroupFolder: ( UIImage * ) image
imageIndex: ( int ) imageIndex
{
assert( NULL != image );

NSData * jpegData = UIImageJPEGRepresentation( image, 1.0 );

NSURL * containerURL = [ [ NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier: APP_SHARE_GROUP ];
NSString * documentsPath = containerURL.path;

// Note that we aren't using massively unique names for the files in this example:
NSString * fileName = [ NSString stringWithFormat: @"image%d.jpg", imageIndex ];

NSString * filePath = [ documentsPath stringByAppendingPathComponent: fileName ];
[ jpegData writeToFile: filePath atomically: YES ];

//Mahantesh -- Store image url to NSUserDefaults

NSUserDefaults *defaults=[[NSUserDefaults alloc] initWithSuiteName:@"group.com.schemename.nameofyourshareappgroup"];
[defaults setObject:filePath forKey:@"url"];
[defaults synchronize];

return filePath;
}

- ( void ) passSelectedItemsToApp
{
NSExtensionItem * item = self.extensionContext.inputItems.firstObject;

// Reset the counter and the argument list for invoking the app:
m_invokeArgs = NULL;
m_inputItemCount = item.attachments.count;

// Iterate through the attached files
for ( NSItemProvider * itemProvider in item.attachments )
{
// Check if we are sharing a Image
if ( [ itemProvider hasItemConformingToTypeIdentifier: ( NSString * ) kUTTypeImage ] )
{
// Load it, so we can get the path to it
[ itemProvider loadItemForTypeIdentifier: ( NSString * ) kUTTypeImage
options: NULL
completionHandler: ^ ( UIImage * image, NSError * error )
{
static int itemIdx = 0;

if ( NULL != error )
{
NSLog( @"There was an error retrieving the attachments: %@", error );
return;
}

// The app won't be able to access the images by path directly in the Camera Roll folder,
// so we temporary copy them to a folder which both the extension and the app can access:
NSString * filePath = [ self saveImageToAppGroupFolder: image imageIndex: itemIdx ];

// Now add the path to the list of arguments we'll pass to the app:
[ self addImagePathToArgumentList: filePath ];

// If we have reached the last attachment, it's time to hand control to the app:
if ( ++itemIdx >= m_inputItemCount )
{
[ self invokeApp: m_invokeArgs ];
}
} ];
}
}
}
- ( void ) invokeApp: ( NSString * ) invokeArgs
{
// Prepare the URL request
// this will use the custom url scheme of your app
// and the paths to the photos you want to share:
NSString * urlString = [ NSString stringWithFormat: @"%@://%@", APP_SHARE_URL_SCHEME, ( NULL == invokeArgs ? @"" : invokeArgs ) ];
NSURL * url = [ NSURL URLWithString: urlString ];

NSString *className = @"UIApplication";
if ( NSClassFromString( className ) )
{
id object = [ NSClassFromString( className ) performSelector: @selector( sharedApplication ) ];
[ object performSelector: @selector( openURL: ) withObject: url ];
}

// Now let the host app know we are done, so that it unblocks its UI:
[ super didSelectPost ];
}

#ifdef HIDE_POST_DIALOG
- ( NSArray * ) configurationItems
{
// Comment out this whole function if you want the Post dialog to show.
[ self passSelectedItemsToApp ];

// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return @[];
}
#endif

#ifdef HIDE_POST_DIALOG
- ( void ) willMoveToParentViewController: ( UIViewController * ) parent
{
// This is called at the point where the Post dialog is about to be shown.
// Make it transparent, so we don't see it, but first remember how transparent it was originally:

m_oldAlpha = [ self.view alpha ];
[ self.view setAlpha: 0.0 ];
}
#endif

#ifdef HIDE_POST_DIALOG
- ( void ) didMoveToParentViewController: ( UIViewController * ) parent
{
// Restore the original transparency:
[ self.view setAlpha: m_oldAlpha ];
}
#endif
#ifdef HIDE_POST_DIALOG
- ( id ) init
{
if ( self = [ super init ] )
{
// Subscribe to the notification which will tell us when the keyboard is about to pop up:
[ [ NSNotificationCenter defaultCenter ] addObserver: self selector: @selector( keyboardWillShow: ) name: UIKeyboardWillShowNotification object: nil ];
}

return self;
}
#endif
#ifdef HIDE_POST_DIALOG
- ( void ) keyboardWillShow: ( NSNotification * ) note
{
// Dismiss the keyboard before it has had a chance to show up:
[ self.view endEditing: true ];
}
#endif
@end

 

2. In the openURL method of your application delegate

  //Slartibartfast -- For the case where we are opening app from an extension
         NSString *STATIC_FILE_HANDLE = @"file://";
        //If app is opened from share extension, do the following
        /*
         1.) Get path of shared file from NSUserDefaults
         2.) Get data from file and store in some variable
         3.) Create a new accesible unique file path
         4.) Dump data created into this file.
         */

        NSUserDefaults *defaults=[[NSUserDefaults alloc] initWithSuiteName:YOURAPP_STATIC_APP_GROUP_NAME];
        NSString *path=nil;
        if(defaults)
        {
            [defaults synchronize];
            path = [defaults stringForKey:@"url"];
        }

        if(path.length != 0)
        {
            NSData *data;
            //Get file path from url shared
            NSString * newFilePathConverted = [STATIC_FILE_HANDLE stringByAppendingString:path];
            url = [ NSURL URLWithString: newFilePathConverted ];
            data = [NSData dataWithContentsOfURL:url];
            //Create a regular access path because this app cant preview a shared app group path
            NSString *regularAccessPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *uuid = [[NSUUID UUID] UUIDString];
            //Copy file to a jpg image(ignore extension, will convert from png)
            NSString *uniqueFilePath= [ NSString stringWithFormat: @"/image%@.jpg", uuid];
            regularAccessPath = [regularAccessPath stringByAppendingString:uniqueFilePath];
            NSString * newFilePathConverted1 = [STATIC_FILE_HANDLE stringByAppendingString:regularAccessPath];
            url = [ NSURL URLWithString: newFilePathConverted1 ];
            //Dump existing shared file path data into newly created file.
            [data writeToURL:url atomically:YES];
            //Reset NSUserDefaults to Nil once file is copied.
            [defaults setObject:nil forKey:@"url"];

        }
    //Do what you want
    }

You’re welcome 🙂
Original: https://stackoverflow.com/questions/32228182/code-to-share-file-path-file-between-a-share-extension-and-ios-app/33795269#33795269

Advertisements
COMPUTER SCIENCE, TECHNOLOGY

Android – Picasso vs UniversalImageLoader vs Glide vs Fresco

Someone asked a question on Stackoverflow the other day about the existence of so many image libraries in Android .

Since this is a pretty opinionated topic, I made a table to represent what I thought about the libraries based on personal experience of having used them or working with people who used them

Screenshot 2015-04-16 19.42.09

(Click on the image for better visibility)

Its interesting to note that Fresco seems to be a new library that is doing some interesting optimizations to memory use and could be worth checking out.

COMPUTER SCIENCE, LIFE

Cheryl’s breaking the internet

Recently this 5th grade olympiad question from Singapore went viral

landscape-1429047682-cheryl

This is pretty difficult agreed for a fifth grader – but being an olympiad puzzle its meant to be difficult and challenging but smart kids can solve it. I wonder why adults are making a fuss out of this one ?

Well it took me about 3 minutes to solve and the solution follows, so solve it before you proceed to the solution bit

Solution:

Lets break it down statement by statement

Days: 

May 15, 16, 19

June 17, 18

July 14, 16

August 14, 15 17

  • Albert says – I don’t know when Cheryl’s birthday is but I know that Bernard does not know too
  1. The first part of the sentence is moot(is it?). Albert cant know yet when told just the month because there are too many variables. The second part is critical
  2. How does Albert know Bernard does not know too? They way to think about this is that for Albert to be confident that Bernard does not know, he must have eliminated cases where Bernard would have to know. What are those cases?
  3. Those cases are essentially if Cheryl had told Albert May or June which means Cheryl had said 18 or 19 to Bernard. In which case Bernard could definitely know.(With me?). But since Albert definitely knows(suspension of the belief that everyone lies) it cant be May or June or 18th or 19th, hence these are eliminated.

Days Left: 

May 15, 16, 19

June 17, 18

July 14, 16

August 14, 15 17

  • Bernard says – At first I don’t know when Cheryl’s birthday is, but I know now
  1. Again another assumption here is that all three are really math savvy. So when Albert hints Bernard doesn’t know he has also figured out the above . Now lets assume Cheryl had said 14 to Bernard, in which there was no way Bernard could have known when the birth month is. But since Albert’s hint about Bernard knowing the date is confirmed, Cheryl couldnt have said 14 to Bernard. Hence eliminating July and August 14th.
  2. The dates left are July 16, August 15, 17 . Now here’s the thing, Bernard has figured out the answer from this clue itself! This is the slightly tricky bit –> He knows the date i.e. 15th, 16th or 17th. Doesn’t matter which month for him really now, because they are all unique.

Dates:

May 15, 16, 19

June 17, 18

July 14, 16

August 14, 15 17

  • Albert: Now I know too
  1. Remember Albert knows the month. For Albert to say this he has deduced the date given the month.  For Albert to know, the month has to be July, because if Cheryl had told him, “August,” then he would still have two possibilities: Aug. 15 and Aug. 17.
  2. Hence Albert also figures out the answer

Which is JULY 16

Here’s the much tougher unsolvable variant, a similar problem called Sum and Product. I wonder if this will break the internet?

Two mathematicians S and P are discussing two unknown integers, both greater than 1. S knows only the sum of the numbers, whereas P knows only their product.:

S: “I see no way you can determine my sum.”

P (after a suitable delay): “That didn’t help me. I still don’t know your sum.”

S (after another delay): “Now I know your product.”

What are the two numbers?

SO link: http://math.stackexchange.com/questions/165311/the-impossible-puzzle-now-i-know-your-product

Quick interesting questions

  • Why did this particular problem go viral? There are a ton of obscure olympiad problems for lower grades?
  • Why are adults finding it hard to solve this problem?
  • How long did this take you to solve?
COMPUTER SCIENCE, STARTUPS, TECHNOLOGY

Interview engineers like a reverse bloom filter

Hiring is hard. Hiring great engineers is harder. But cleaning up bad engineering work from bad hires is the worst!

If you are an engineering manager like me, its your responsibility to hire engineers and generally set the bar very very high for candidates. The most obvious well known trick is to hire people smarter than you(The whole A’s hire A+’s, B’s hire C’s thing). But many a times, especially in startups or service companies, due to high pressure demands, this bar can go down and there is nothing worse.

There a lot of the times engineers can be false positive -i.e. they come across as brilliant in the interviews. Many a times this is because engineers are extremely well prepared specifically for interviews(having gone through the thousand of resources available online, the data set of available questions,unheard of yet, is bound to get smaller)

So , interviewing has to model a bloom filter in reverse

Background on a bloom filter:

During the process, you are probably involved in a couple of rounds with the interviewee, but in general its your engineers who interview potential candidates. Engineers understand engineering terms better. Hence we should be modelling the process and communicating to the engineer similarly.

Bloom filter.svg
Bloom filter” by David Eppstein – self-made, originally for a talk at WADS 2007. Licensed under Public Domain via Wikimedia Commons.

A Bloom filter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not.

The idea is that a query for an item returns either “possibly in set” or “definitely not in set”. Elements can be added to the set, but not removed (though this can be addressed with a “counting” filter). The more elements that are added to the set, the larger the probability of false positives. Plus a bloom filter is a great data structure particularly if you are using strong caching mechanisms. Hence you’d do good getting your engineers to learn a swanky data structure while they interview other candidates.

How does this apply to interviewing:

Applying this to an engineering candidate is interesting. You have to be biased towards false negatives, false positives should not make it. Ala a reverse bloom filter, which could say a candidate should be looked at as  “Great but wont make it” and not “OK should make the cut” or False negatives are possible but false positives aren’t.  Essentially this says, its OK to lose very very good engineers who don’t make the cut(but certainly are great), but its absolutely not ok to hire bad eggs on a false curve. The cost and time spent on training and cleaning up behind these engineers can get exponentially higher than the time spent carefully interviewing candidates and selecting the right one. 

Might be a convoluted way to think about it,  but it’s worked so far for us. 🙂

Comments welcome. Ok maybe instead of a reverse bloom filter I could have said a lossy hash table or a LRUCache or even a direct mapped cache. But they don’t sound as catchy 🙂

COMPUTER SCIENCE, STARTUPS, TECHNOLOGY

16 Things

Andreessen Horowitz

We don’t invest in themes; we invest in special founders with breakthrough ideas. Which means we don’t make investments based on a pre-existing thesis about a category. That said, here are a few of the things we’ve been observing or thinking about; we’re especially grateful to our founders/companies, and the entrepreneurs we meet with everyday, for their insights here…

[For other trends we’ve covered already elsewhere, please see our series on mobile eating the world (with lots of charts!), you bet your SaaS, and government x tech.]

View original post