Skip to content

Commit

Permalink
Handle invalid URLs on iOS, instead of crashing
Browse files Browse the repository at this point in the history
Before, when loading a non-image (e.g. a 404 html page), the code/app would crash because function `contentTypeForImageData` would return `nil` as the file extension, which was not accepted by `NSURL.URLByAppendingPathExtension`.
Now, the spinner will disappear, and a simple alert will be shown.
  • Loading branch information
paulklinkenberg authored Aug 21, 2018
1 parent 952ee8d commit 329d8c4
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/ios/PhotoViewer.m
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ - (void)show:(CDVInvokedUrlCommand*)command
});
}

} else {
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicator stopAnimating];
[self closeImage];
// show an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Photo viewer error"
message:@"The file to show is not a valid image, or could not be loaded."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
});
}
}];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
Expand All @@ -125,13 +137,19 @@ - (NSURL *)localFileURLForImage:(NSString *)image
NSURL* fileURL = [NSURL URLWithString:webStringURL];

if (copyToReference && ![fileURL isFileReferenceURL]) {
NSData *data = [NSData dataWithContentsOfURL:fileURL];
NSError* error = nil;
NSData *data = [NSData dataWithContentsOfURL:fileURL options:0 error:&error];
if (error)
return nil;

if( data ) {
// save this image to a temp folder
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSString *filename = [[NSUUID UUID] UUIDString];
fileURL = [[tmpDirURL URLByAppendingPathComponent:filename] URLByAppendingPathExtension:[self contentTypeForImageData:data]];

NSString *ext = [self contentTypeForImageData:data];
if (ext == nil)
return nil;
fileURL = [[tmpDirURL URLByAppendingPathComponent:filename] URLByAppendingPathExtension:ext];
[[NSFileManager defaultManager] createFileAtPath:[fileURL path] contents:data attributes:nil];
}
}
Expand Down

0 comments on commit 329d8c4

Please # to comment.