Tuesday, June 14, 2016

Setting up a Google Play Expansion File (.obb) for easy Android WebView reference

Scoping the problem

A PhoneGap app I'm working on has a lot of image and sound files.  We have the iOS version working fine, but the Android version is roughly 200MB, a full 100MB over the maximum binary size allowed by Google Play.

Google Play tells us that we can create a separate ".obb" (Opaque Binary Blob) expansion file where we can offload some of that content.  The OBB is uploaded along with the APK,

Ok, sounds great.  But before creating the OBB, I know I'm going to have to access the files in the OBB from HTML passed to an Android WebView.  Ideally,  we want simple file references without writing a lot of code.  For example:

<img src="file://SomePathToOBB/photos/photo1.png">

I didn't want to have to unpack the OBB, so after doing some Stack Overflowing, here and here, I decided to pursue this SO suggestion:
It is a good alternative to use JOBB tools to pack expansion file and use StorageManager to mount it. After that the files inside expansion file should be accessible as regular files in the file system. The unpacking of expansion file is not needed in this case.
An OBB file can be of any type (.pdf, .zip, etc), but a file created with the JOBB utility can be mounted using StorageManager and requires no extra work at runtime (like extracting from a zip file).

Creating the .obb using JOBB & loading on a test device

To create the .obb, I moved directories of image files into a directory named materials, and then ran the following* from the command line on my Mac:
/Users/mikem/Library/Android/sdk/tools/jobb -d materials -o my.obb -pn com.gwhizmobile.example -pv 1
* com.gwhizmobile.example represents the app package name

Easy!  The OBB was created as my.obb.  According to my reading of the docs, when I upload it to Google Play, it will automagically rename the file into something like main.1.com.gwhizmobile.example.obb.  However, I wanted to be able to test it on my Nexus 5 test device, so I renamed it into the proper format, and put it into a directory structure with the following path:
./obb/com.gwhizmobile.example/main.1.com.gwhizmobile.example.obb
This structure allowed me to use the Android File Transfer utility for Mac to copy the obb directory onto my device (in the Android folder)

So at this stage, I have the .obb file built and residing on my Nexus 5 where it is supposed to be.

Using Storage Manager to mount the .obb and get contents path

Next, we need to add some code that allows us to mount the obb.  Between here and here, I generated this little snippet of code**:
    
  String pathReference = null;

  final StorageManager storageManager = (StorageManager) context.getSystemService(context.STORAGE_SERVICE);
 
  final String packageName = "com.gwhizmobile.example";
  final String packageVersion = "1";

  final File mainFile = new 
 File(Environment.getExternalStorageDirectory() +  "/Android/obb/" + packageName + "/"+ "main." + packageVersion + "." + packageName + ".obb");

  storageManager.mountObb(mainFile.getAbsolutePath(), null, new  OnObbStateChangeListener() {

     @Override

     public void onObbStateChange(String path, int state) {
       super.onObbStateChange(path, state);
       if (state == OnObbStateChangeListener.MOUNTED) {
         pathReference = storageManager.getMountedObbPath(path);
       }
    }
  });

** Since this is a PhoneGap app, this code was encapsulated within a simple homegrown Cordova plugin.

Final integration steps

The generated pathReference value looks something like file:///mnt/obb/123e187987192397831.  This is the prefix we can use in the HTML, as in:
 <img src="file:///mnt/obb/123e187987192397831/photos/photo1.png">
Works. Like. A. Champ.

A few other notes

  1. Although we created the .obb by pointing it at the materials directory, that directory name is not included in the filename path.
  2. GooglePlay will not allow you to upload the OBB file with your first APK!?  However, after doing another build process the OBB can be loaded.
  3. Note that the packageVersion in the code above will need to change since GooglePlay will rename the OBB file to the version of the APK loaded at the same time as the OBB.



Thursday, March 24, 2016

A Guide for Engaging in Political Discussions and Not Looking Like an Idiot

During this 2016 political season, there's been a distressing outbreak of bad grammar, misspellings, mangled abbreviations, and poor reasoning on political websites and Twitter.   Although the offenders are largely from Team Trump, there's a fair amount from other camps as well.
With that in mind, I consider it my patriotic duty to improve the political discourse in these United States, and I'll address that obligation in the form of this blog post.  :)  I welcome comments, suggestions, and corrections.

Disclaimer:  I don't pretend to be a grammarian, and some of this writing probably violates at least a few rules in The Little Brown Handbook - but somebody must take the first step - it might as well be me!

Here goes, and may God bless America (and keep her literate).

GRAMMAR

You're is the shortened form of you are, not  your.  Your is a possessive, as in: Your lack of basic grammar skills makes it seem like you should be in summer school instead of commenting on presidential politics.

They're is the shortened form of they are.  Their is a possessive - for example, they are wasting their vote if they vote for your guy.  Additionally, there refers to a place, as in, there they go again.  

SPELLING

States do not succeed from the union, they secede.   Perhaps they successfully seceded?

Conceded does not mean the same thing as conceited.  All of us cool kids know this already.

If you use loosing when you should have used losing then you've already lost.

Lieing is not a word and I ain't lying.  Same with lier.

The problem with illegal immigration is not boarder security, but border security.  (Unless you're referring to a lack of rooms in your house).

Traders and Traitors are not the same.  Traders trade;  Traitors don't trait.


ABBREVIATED WORD MEANING
  
There is no such thing as a Super Pack unless you're talking about these.  You are probably referring to a super PAC, where PAC stands for Political Action Committee.

A Rhino isn't the same as a RINO (Republican In Name Only).  That thing on my face is a nose, not a horn. (although I can understand the confusion)

i.e. and e.g. are not the same.  i.e. (id est) translates to "that is", and e.g. (exempli gratia) means "for example".


REASONING & ARGUMENTS

Starting a sentence with The fact is... implies that it will be followed by verifiable facts, not opinions. 

Never use never and always avoid always - Using these adverbs weakens your argument since they are usually logically false.    For example, saying something like "Conservatives never treat poor people fairly" or "Liberals always hate America" is demonstrably untrue.

Don't use strawman arguments (setting up a false proposition and then knocking it down).   "Even though liberals want to take all of our guns, we need those weapons for self-defense!".   "Even though conservatives want poor people to die early, we still need universal health care!"

Calling someone a dumb-ass, liar, or other school yard taunt will not help your cause.  It may make you feel better, and may even be true, but it will shut down any hope of educating your opponent to your point of view.   What is the point of arguing if not to make your opponent see the light (or perhaps learn something)?

NOT A WORD

Hugely



Thursday, February 18, 2016

Facebook Audience Network Ad Approval

(Feb/2016)

I've been working on integrating Facebook Audience Network ads.    Before going "live", Facebook says that they have to approve the ad placement - they say this approval is initiated automatically when you've had 5 successful test ads and that the approval takes 2-3 business days.

In my case, I displayed some test ads on the simulator, and also on a device.  They tell you to use the API and register the device with a hash code they provide.

After almost a week, I hadn't heard anything from Facebook and was wondering what was going on.  After doing some online research, I found a discussion that suggested that the number of impressions was important.

I reran the app - this time with it running on a local device connected to Xcode.  On each refresh, it would write  [FBAudienceNetworkLog/FBAdUtility:396] Impression is logged (displayed for test ads only)  to the console. 

I let it go for a few minutes until there were at least five of these impressions.

Then, to my surprise, less than a minute or two later, I received a Facebook alert saying that the app had been approved.

I had a second app that I repeated the process with.  Again, after just a few minutes, the app was approved for ads.

*** Update 3/28 ***

Okay, after doing a few more apps, it seems that Facebook has changed the process such that they just automatically review apps after a few days.    I'm guessing that the number of impressions still matters, but it seems disassociated from when they actually review. 

Thursday, October 22, 2015

iOS 9 Issues

This is just a list for keeping track of iOS 9 related issues I've run into.


1) If you get a list of font families, some of those families do not contain any actual fonts - only seems to affect newer devices.  (reported to apple - marked as dupe)

2) Weird issues with UIView hit test not propagating.   Oddball things where it works everywhere but on an iPhone 6s.  Generally, once recompiled, it works fine.  Actually, I've found that recompiling or changing the hit test code does not work.  In fact, any old style touchesBegan type tap handling does not work on the iPhone 6s.

3) CSS Sibling selectors do not work in certain conditions, for example:

input:checked + label ~ div {
    z-index: 1;
}


changing to:

input:checked + label + div {
    z-index: 1;
}


does work, but doesn't work in iOS 8.   Adding both rules seems to do the trick.

4) Using willRotateToInterfaceOrientation to force a UISplitViewController to refresh the layout no longer works.  Should use  setPreferredDisplayMode instead, as in:

    [sv setPreferredDisplayMode:(hideMaster)?UISplitViewControllerDisplayModePrimaryHidden : UISplitViewControllerDisplayModeAllVisible];

for example.

5) External http calls not working (after iOS 9 recompile).  Need to add

NSAppTransportSecurity
   NSAllowsArbitraryLoads  : YES

to info plist.




Tuesday, October 6, 2015

How to use the UIFocusGuide for navigation

I really didn't quite understand how UIFocusGuides were supposed to work until after several hours of banging my head against the wall.  I think I got it now....

The focus guide, like the layout guide it extends, can be thought of as an invisible view - in this case, an invisible focusable view.

A UIFocusGuide functions as a bridge between different areas of the screen since focus navigation only works up/down or left/right.

Consider a screen that has two objects A and B.  

     AAAA

               BBBB

With the default focus behaviors, there is no way to transition from A to B because B is not directly to the right or bottom.

Thus, to make this work, you'd need a focus guide in between, like


     AAAA

FFFFFFFFFFFFFFFFFFFFF

               BBBB


and we would set the focus guide's preferredFocusedView = B to start.  

So, given this example layout, if view A has the focus, and the user navigates down, it will find the focus guide (F), and the focus guide will then redirect the focus to the guide's  preferredFocusedView, in this case B.

Of course, if B has the focus, you'd want to update the focus guide so its preferredFocusedView is now A, so that when the user navigates up, it goes from B to A.

Okay, now that you get the concept, what's the code look like?  Something like this (Warning: I have not compiled/run this segment):


UIFocusGuide *F;

- (void)viewDidLoad
{
   [super viewDidLoad];
   
   F = [UIFocusGuide new];
   [self.view addLayoutGuide:F];

   [F.topAnchor constraintEqualToAnchor:A.bottomAnchor].active = YES;
   [F.heightAnchor constraintEqualToConstant:1].active = YES;
   [F.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
   [F.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;

   [F setPreferredFocusedView:B];
}
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{

   if (context.nextFocusedView == A){
       [F setPreferredFocusedView:B];
   } else if (context.nextFocusedView == B){
       [F setPreferredFocusedView:A];
   }
}


Apple has a simple example in the UIKitCatalog demo that demonstrates the concept in swift.  The layout in that example case is more like:

AAAAA    BBBBB

CCCCC    FFFFF

and it shows the navigation between B and C via F.

Monday, August 31, 2015

Upload a file to Google Drive via PHP using REST

Disclaimer: I am (at best) a novice PHP coder.  There may well be better ways to accomplish this task, but this is what worked for me.

First off, Google does provide a nice-looking PHP library for working with Drive, but I was reluctant to introduce more libraries into our already complex and fragile server environment.

Using REST, Google's  documentation explains that there are three ways to upload files to Drive - using a media upload, a multipart upload, and a resumable upload. 

For our task, we were working with small spreadsheets so the resumable upload was overkill.

We really wanted to use multipart but gave up after many hours of trying but getting only 400 - Bad Request errors.  We tried using the exact type message that Google detailed in its documentation, but it still didn't work.   (Had I been a better PHP programmer, perhaps I could have figured out what was wrong).

Anyways, we moved on and used a combination of a media POST, to upload the file contents followed by a PATCH, to update the title.  Here's the code:


POSTing the file to upload.  (Assumes you have an authorization token).  The result of the file_get_contents call will be a JSON structure that represents a file resource.


$authstr = 'Bearer '.$token;

$fileToUpload = "datafiles/".$_FILES['uploadedFile']['name'].".csv";

$url = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true'; 

$options = array(
        'http' => array(
            'header'  => "Content-type: application/vnd.ms-excel\r\nAuthorization: ".$authstr."\r\n",
            'method'  => 'POST',
            'content' => file_get_contents($fileToUpload),
        ),
 );
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$json = json_decode($result);


PATCHing the file to change the title.  We use a different URL here and identify the file using the File Id returned from the media upload POST.  We tell it that we're passing a JSON structure and send along the attributes to change.


$url = 'https://www.googleapis.com/drive/v2/files/'.$json->id;
 

$options = array(
        'http' => array(
            'header'  => "Content-type: application/json\r\nAuthorization: ".$authstr."\r\n",
            'method'  => 'PATCH',
            'content' => '{"title" : "My New Filename"}',
        ),
 );

$context  = stream_context_create($options);

$result = file_get_contents($url, false, $context);
$json = json_decode($result);



Have a better solution?  I'd be interested to hear about it....




Thursday, May 28, 2015

Backing up Cordova databases, local storage, and CDVLocalStorage on iOS

On iOS, Cordova has a complex class, CDVLocalStorage which manages backup behavior via the BackupWebStorage flag.   It was a little hard to understand the gist of what was going on, so I'm describing the general process of how it works here.... Of course, please note that this information has a limited shelf life due to new releases of Cordova and iOS.

Another note is that if you're building with Xcode, the  BackupWebStorage flag is in the config.xml in the Staging area.

Anyways, there are three available values, none, local, and cloud.

When set to none, Cordova does very little and defers to the default iOS behavior which is to store local storage and WebSQL databases in Library/Caches.  This is an area which will not be backed up using iCloud. 

local has the most complex activity.  When set to local, Cordova adds a listener so that when the user exits the app, the databases and local storage will be copied to the Documents/backups directory.  This allows a user plugging their device into their computer and running iTunes backup to save those databases/local storage.  However, to prevent the iCloud backup from copying these files, the Documents/backups directory is marked with the "do not backup" flag.

When BackupWebStorage is set to cloud, the following is set:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"WebKitStoreWebDataForBackup"];

This flag causes iOS to move the databases/local storage files from Library/Caches to Library/WebKit.  Once there, the databases/local storage will be picked up by the iCloud backup.


CDVLocalStorage also creates various Cloud/NoCloud directories but it appears that none of these are ever used.

Thursday, December 4, 2014

A few more autolayout tips and tricks



1.  If you add an view to a container without specifying constraints to derive width/height  it will use the object's intrinsicContentSize.   This is nice if you want to maintain the aspect ratio of the view. 

2.  I have wasted many hours of my life that I'll never get back spent gobs of time attempting to mix IB Autolayout with programmatic constraints.  The problem is because IB automatically inserts its own constraints (thanks IB!) which then conflict with the ones that I'm trying to set (See #3 below).

Several StackOverflow posts recommend checking off the "Remove at build time" flag for constraints that should be set or adjusted programmatically.  That will work, but it means I'll always have to programmatically add that constraint - but sometimes the default IB constraint is fine until something else in the layout changes (e.g., a view is added or removed)

In that situation, just set the priority of the constraint in IB to "High" (vs "Required").  That way, if you add a constraint that conflicts with the default IB constraint, you won't get bad layouts or error messages.

3. Programmatically removing all of the IB built-in constraints for a given view seems to be beyond my technical abilities.  In some situations, no matter what I do, I just can't seem to get rid of those @#!$&$! default IB constraints.  See #2.

4. You can add the same constraint numerous times without error.  I'll leave it up to you to decide if that's a good thing

5. And so I don't forget,  here's how to position two views at 25% and 75% of parent width with programmatic constraints:

   [buttonPanel addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:buttonPanel attribute:NSLayoutAttributeCenterX multiplier:.5 constant:0]];

   [buttonPanel addConstraint:[NSLayoutConstraint constraintWithItem:button2 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:buttonPanel attribute:NSLayoutAttributeCenterX multiplier:1.5 constant:0]];

Tuesday, September 9, 2014

Venting on the iOS8 iTunesConnect


I've had a few app updates in the queue for about 10 days now.  I put them in before the big itunesconnect UI change.  One of them was finally reviewed but rejected yesterday for crashing after startup.  Naturally, I can't reproduce the error but with the given crash logs I tweaked some code and resubmitted.

Then I went into iTunesConnect and could not find my binary.  Ah, wait - it's here under "Prereleases".  It says that it is "processing".  It's already been validated.  "Processing"?   What can it possibly be doing?  Theories abound:
  1. Each byte is meticulously separated and dropped into a "bit bucket" which then tips over and causes a matchbox car to go down a ramp, triggering a fan, which expands a small red balloon, thus delighting the children of Apple employees.
  2. The binary is transmitted to CIA for insertion of  top secret code which turns my flashcard app into a Morse code messenger for international spies.
  3. It's standing in the TSA line at Denver International Airport.
After some quick Goog research I find out that we have to wait for the "processing" step to finish before we can do anything else.

So, six hours later, the sprinkled unicorn dust finally settles on the build and it is done "processing".    Unfortunately, this occurs at 2AM, and like all good developers, I'm in bed, dreaming of a better world where these fancy, newfangled computer thingies are smart enough to sheperd a binary through the process all by itself.

In the "Prereleases" list, my newly blessed magical "processed" binary shows a little   !  in a box with no explanation.   Clicking/Hovering over it makes no difference.     Is it tired? Unhappy?

I add the binary to the app record, and go to subm -  ah, no.  Requires a "Save" first, then I can resubmit.   Because, you know, I might want to add a build and then get a sandwich before attempting that last, exhausting, tap-the-submit-button step.

I have three other apps "Waiting For Review" that are not even showing up in the app list as that status.   Another one that says it's "Waiting For Review" but it was actually approved before the UI change.    Yay! There are no rules!  Pick your own status!

Monday, July 7, 2014

UIWebView issue with links only being called once.



We use UIWebView's pretty heavily in our apps.  Sometimes we use links in a page to invoke other behaviors, like pushing another UIViewController on to the navigation stack.

We noticed recently that, on an iPad, clicking such a link, popping the navigation stack, then trying to click the link again did not work.

With some investigation, it seems that the delegate method shouldStartLoadWithRequest was only being called the first time.  If another link on that same page was clicked, it would work fine; the problem only occurred when the same link was attempted two or more times consecutively.

It seems the issue is that, even if you return NO from shouldStartLoadWithRequest, UIWebView believes that the requested link is the currently viewed page - thus, clicking the link again takes no action since UIWebView thinks that it's already there.

To fix this, I found the following StackOverflow link - it describes a similar problem.  The workaround to fix the issue is to fool UIWebView into believing that it is somewhere else by using javascript to change its location.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 


    NSString *surl = [[request URL] absoluteString]; 

    NSRange r = [surl rangeOfString:@"#MYACTIONLINK"]; 
    if (r.location != NSNotFound){ 

    // do my custom action
        [[NSNotificationCenter defaultCenter] postNotificationName:NotifyHTMLViewerSelectedLink object:nil userInfo:nil]; 

        [webView stringByEvaluatingJavaScriptFromString:@"window.location='#__DUMMY_ANCHOR'"]; 
    
        return NO; 

    } 

    if ([surl hasSuffix:@"_DUMMY_ANCHOR"]) 
        return NO; 

....

Thursday, March 13, 2014

Percentage based layouts using (mostly) Xcode IB and Autolayout

The Xcode lnterface Builder (IB) doesn't provide a clear way to handle a percentage based layout - for example, a screen where one view takes up 25% of the width of the screen, and the other view gets the rest.

---------------------------------------------------
|                    |                                              |
|                    |                                              |
|                    |                                              |
|        A         |                       B                     |
|                    |                                              |
|                    |                                              |
|                    |                                              |
---------------------------------------------------

Here's one way to use IB for all but a few lines of code.  (based on ideas from this stackoverflow post.)

For "view B", using Xcode IB, I put constraints on the top, right, bottom, and left
For "view A", using Xcode IB, I put constraints on the top, left, bottom, and then set the width to a fixed size.  I edited the width constraint of "view A", and checked the "placeholder remove at build time" checkbox.

then, in the view controller's viewDidLoad, I added these two lines:


    NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:viewA
                           attribute:NSLayoutAttributeWidth
                           relatedBy:NSLayoutRelationEqual
                            toItem:viewA.superview
                            attribute:NSLayoutAttributeWidth
                            multiplier:.25
                            constant:(CGFloat)0];
   

    [viewA.superview addConstraint:c];



This just makes viewA 25% of the size of it's superview.  Since viewB is tied to viewA's width, it also adjusts properly without having to specify extra constraints for it.

Tuesday, March 11, 2014

iOS 7.1 issues


x. Noticed that the tab bars don't work quite the same way.  I have an .xib that I use for both iPad and iPhone layouts.  With 7.1, the tab bar now appears to be larger on the iPad (56 pixels) but the .xib doesn't auto adjust the 'y' for the former size (which was 49 pixels).  What this does is make the tab bar looked clipped at the bottom on the iPad. 

The fix requires using autolayout to set up the tab bar.  Then it works for 7.1 and prior versions.   An alternative fix is checking the tab bar's y value in the view controller's viewWillLayoutSubviews method to make sure it is equal to viewController.view.frame.size.height - tabBar.frame.size.height;

x. In previous versions, setting the corner radius and border on a layer would implicitly mask that layer to the corner arcs.  This is no longer the case in 7.1.  Now, if you set the background color of a UIView, and then set the corner radius and a border, the border will show the corner arcs, but the background color will extend to the square corners.


x. Not sure if this is a 7.1 only, issue but noted that an application that used to work okay is now getting a weird autolayout error on the iPad when dismissing a modal view.  There's tons of unhelpful error diagnostics and it ends with:
 
Cannot find an outgoing row head for incoming head UILabel:0x1462c580.Width{id: 414}, which should never happen.'

I saw a few mentions of this error on the web but no real help.  I was able to avoid the error by changing the constraints on one of the ViewControllers' UILabels.  Originally the UILabel was constrained to top right left with a fixed height.  It works if set to top width height centered x.     I doubt that this is the "real" solution, but I wasn't able to find anything else that seemed to be the issue.   (Ugh. There's three hours of my life I'll never get back).

Update: Ran into this error again and burned another six or so hours.  It seems related to percentage based views in autolayouts but I haven't been able to narrow it down much further than that.


Sunday, February 16, 2014

PERL Matching non-ASCII characters in a converted RTF

I have a data file that was converted from an RTF to a TXT.    When I started trying to parse it using PERL, my regular expressions weren't able to split up lines that looked like they had whitespace delimiters - It would just ignore the whitespace.

After my initial confusion, I figured that the whitespace must be something other than an ASCII space character, tab, etc.   By some experimentation, I noticed that there were several bytes being represented in that "whitespace".

To try and figure out what the bytes/characters were, I created a little PERL code segment that looked like:

while ($filecontents =~ /([^\d\w\s\t\.:;&\,\-\(\)]+)/){
    $f = $1;
    $d = $1;
   
    $f  =~ s/(.)/sprintf("%x ",ord($1))/eg;
    print "f is $f\n";
    $filecontents =~ s/$d/zzz/g;

}


Basically, the code goes thru the file, finds oddball characters and prints them out.  When I ran it, it produced the following:

   f is e2 80 83
   f is e2 80 a8
   f is e2 81 84
   f is c2 b0 

 
Note that each of those looks like a multi-byte character, but what are they?

Well, I do love the internet.  I cut and pasted e2 80 a8  into Google and found that it was an "em space", aka Unicode character \u2003.

Once I was able to get the Unicode character, I could just replace all of the em spaces with a regular space, and the rest of my program worked as designed.  Same idea with the other special characters.  Two of those characters were not whitespace, but were non-ASCII characters as well (fraction slash and degree symbol).

Note that, at least in my case, I had to match using the hex versus the unicode character. In other words

    $filecontents =~ s/\xe2\x80\xa8/ /g;

I'm assuming this is because the Unicode would be a UTF-16 character but I'm dealing with a UTF-8 encoding?   For next time, I should see if I can export the RTF to a UTF-16 text file.  Maybe it would be easier :)

Monday, February 10, 2014

UIWebView, URL history, and redirects

Sometimes it seems the simplest things turn out to be much more complicated than they should be.

In several of our apps, we include help files written in HTML which are loaded locally from the bundle into a UIWebView.  Sometimes those help files contain links to web pages.

The problem is that UIWebView doesn't treat locally loaded webpages as part of the history stack.  Thus if the user clicks a link and visits a web page, there is no simple way for the app to return to the original locally loaded HTML file because [webview canGoBack] returns NO.  Grr.

My first attempt to deal with the issue was to just reload the local file if [webview canGoBack] was NO.  However, if the same locally loaded HTML file contains two web pages, and the user visits each, after the attempt to return from the 2nd webpage,  [webview canGoBack] will return YES and [webview goBack] will display the first webpage, because the first webpage was never removed from the UIWebView's history, and there's apparently no way (that I was able to find) to get rid of it.  Grrr.

The next step was to try and maintain my own count of visited URL's and back out of them as the user clicked the back button.   I implemented this by adding to the count in the UIWebView delegate method shouldStartWithRequest when the navigationType was UIWebViewNavigationTypeLinkClicked and removed them with each click of the back button.  Great!  Except that redirects also load with a navigationType of UIWebViewNavigationTypeLinkClicked so the user would have to click "back" several times for no clear reason because the link count was incremented for each redirect.  Grrrr.

I was able to finally make it work with some insight from this tutorial.  The key I learned was that  the webViewDidFinishLoad delegate method is not called until the redirects have been resolved. (But it may call the method several times as it loads the contents of the page).

Below are the key elements of the code:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
   
    // we use the linkClicked boolean because with redirects, this method is still called multiple times and we only want
    // to increment once.
    if (linkClicked == NO && navigationType == UIWebViewNavigationTypeLinkClicked){
        linkClicked = YES;

        if (linkStack == 0){
            scrollOffset = webView.scrollView.contentOffset;
        }
        linkStack++;
    }
   
    return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (linkStack == 0 && scrollOffset.y > 0){
        // reset the scroll if we are coming back to a page after a clicked link.
        [wv.scrollView setContentOffset:scrollOffset];
        scrollOffset = CGPointMake(0, 0);
    }
   
    NSURLRequest* request = [webView request];
    if ([[request mainDocumentURL] isEqual:lastMainDoc])
        return;
   
    linkClicked = NO;
    [self setLastMainDoc:[request mainDocumentURL]];
   
    NSLog(@"finished loading %@", [[request mainDocumentURL] absoluteString]);
   
}

-(void)doBack:(id)sender
{
   
    if (linkStack > 0){
        if (linkStack == 1 || [wv canGoBack] == NO){
            [self loadFile];

        } else {
            linkStack--;
            [wv goBack];
        }
        return;
       
    }
}


- (void)loadFile
{
    // load local HTML file
    //....
}



I'm sure there are a few other ways to address this problem, but this is what worked for me....

Friday, February 8, 2013

Using -webkit-tap-highlight-color

In earlier versions of mobile safari  if you used -webkit-tap-highlight-color on a link, you'd also have to specify the active color.  That would give you a nice contrast.  However, since about iOS 5 that no longer works - both the foreground and background are set to the highlight color.

To be able to see the text now, it seems that you need a transparent color.  This works:

-webkit-tap-highlight-color:rgba(26,26,26,.5);


Wednesday, February 6, 2013

Wrapping text around an image AND stopping the wrap.


I like being able to use HTML to wrap text around images.  It looks professional and it's a simple way to inject some cool in an HTML page.

However, sometimes the image is bigger than the text, and at that point you may want to start a new paragraph that is beyond the image.  I was never able to find out how until today:  Just needs

<BR CLEAR="left"> 


See? Down here now! Note that "left" can be other values (e.g., "right","all") to configure appropriately.

Friday, February 1, 2013

Using Google TTS (text to speech)

I was doing some investigation on Text-To-Speech (TTS) for iOS and found a little snippet of code that could be added to any app for some quick TTS.

The catch is that it's limited to just 100 characters and you never know when Google might pull the plug on it, but still, it's pretty cool.


#import <AVFoundation/AVFoundation.h>

...

    NSString *linkTTS = [NSString stringWithFormat:@"http://translate.google.com/translate_tts?tl=en&q=%@",@"this+is+really+quite+cool"];
   
    NSData *dataTTS = [NSData dataWithContentsOfURL:[NSURL URLWithString:linkTTS]];
   
    AVAudioPlayer *_googlePlayer = [[AVAudioPlayer alloc] initWithData:dataTTS error:nil];
    [_googlePlayer play];

Friday, June 15, 2012

Add Localized Help Files Maintaining Subfolder Hierarchy in XCode 4

One of my projects has localized help files for the app.  When the help was originally designed, it was put into subfolders for major help topics.  That didn't really cause any problems until I migrated it into XCode 4.  There it took a little bit of experimentation before I figured it out.

Basically I had to
  1. Click on the target
  2. Select File->Add Files to...
  3. Add the en.lproj/help directory and then make sure to Create folder references for any added folders
  4. Then, select the newly created blue help item in the project navigator and then click on the File->Add Files to.. for the other languages (e.g., es.lproj/help) etc.  If you try to do this by clicking on the target first (instead of the help item in the navigator) it'll cause a compiler error since it (apparently) tries to overwrite the subdirectories

Wednesday, April 25, 2012

WWDC 2012 - A Guide For Those That Can't Go

For those of us that didn't get WWDC tickets, I've decided to write up some tips to make us feel like we're there (based on my experience the last two years). So let's keep our chins up, eh? Here goes:

    NOW

  1. Send me $1600.00. Part of WWDC's mystique is writing a large check for others to tell you what to do. This is a necessary step. Make sure you do it.

    THE DAY BEFORE

  2. Register. Have your S.O. misspell your name on a small piece of paper and attach it with a shoestring. Write WWDC 2012 on a piece of clothing (jacket, t-shirt) and wear it EVERYWHERE for the next five days.

    THE FIRST DAY

  3. Form a single file line outside of your house (you may need to draw on kids, pets, etc). This will simulate the early gathering of dedicated engineers outside of Moscone before the keynote speech. While Tim Cook might not be as big of a draw as Steve was (RIP Steve), you may still want to get in line no later than 11PM the night before; you'll want to be able to sit up front.

    If you can get a neighbor to walk down your "line" and offer you magazines no one reads, that would be ideal.

  4. Once inside Moscone (your house) walk into a small closet filled with clothes, lukewarm coffee, a few bagel fragments and a banana. This represents the "pre-keynote" activity where everyone is standing in the grand hallways. It does get a little tight. Stand there until you get tired, and then sit down and pull out your laptop. Complain about the Wifi.
  5. After 50 minutes or so, get up and walk out of the closet and go upstairs for the keynote. Hurry and find a seat. Stragglers will need to stay downstairs in "the overflow room" since the ballroom will be filled.
  6. When the keynote starts, you may find yourself clapping for no particular reason. Write something clever on your iPad and hold it over your head. Smile a lot. You're at WWDC!!!

    POST-KEYNOTE LUNCH

  7. Go downstairs. Form a line in front of a table with 5000 boxes of food. After 15 minutes, grab a box of food and attempt to find a seat. Sit on the floor if there are no tables. You can get a drink but, for maximum realism, you should only stock Diet Sprite.

    ATTEND A SESSION

  8. Pick a session and form a line outside your den.

    Uh oh. You're turned away at the door; this session is full. Stand in line outside your bedroom instead. Listen to a session talking about hardware optimization on the Newton. It's okay to leave early.

    OTHER ACTIVITIES

  9. Set up a pseudo Apple knick-knacks and branded clothing store. Be sure to overcharge yourself.

    ATTEND THE THURSDAY NIGHT EVENT

  10. Hang out with 5,000 of your closest friends and listen to a band only five of you have ever heard of. Smile a lot. You're at WWDC!!!
Seriously though, I enjoyed (and learned a lot at) WWDC the last couple of years. Maybe I'll go again next year :)

Saturday, April 7, 2012

presentModalViewController prevents release of other view controllers

Not totally sure what's going on, but I have a split view with a control panel on the left and a detail panel on the right. I have a situation where I want to clear the detail panel and then popup a modal view controller. However, it looks like the modal view controller is somehow causing another retain to be added to the view controller in the detail panel, and then it never releases it.

If I clear the detail panel AFTER calling presentModalViewController, then the detail panel view controller is cleared normally.