This must be be accomplished almost completely within JavaScript and then have the result passed back into Objective C. If you have control of the content you are showing, you can add this function into a <script>
tag. Otherwise you will need to inject it as described in this post.
function rectsForSelection() {
var i = 0, j = 0;
var allSelections = window.getSelection();
var result = []; // An empty array right now
// Generally, there is only one selection, but the spec allows multiple
for (i=0; i < allSelections.rangeCount; i++) {
var aRange = allSelections.getRangeAt(i);
var rects = aRange.getClientRects();
for (j=0; j<rects.length; j++) {
result.push(rects[j]);
}
}
return JSON.stringify(result);
}
Then from your Objective C code, you use do something like this:
NSString *rectsString = [webView stringByEvaluatingJavaScriptFromString:@"rectsForSelection();"];
NSData *rectsData = [rectsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *rects = [NSJSONSerialization JSONObjectWithData:rectsData
options:0
error:NULL]; //Do Your Own Error Checking
I'll add that this will get coordinates that are valid within your webView.scrollView
, not your webView
.