I am wanting to use a UIWebView to do some manipulation of a web page.
I've added all the necessary UIWebView code to an NSObject class but the UIWebView delegate methods are never called and it seems to not do anything at all.
If I transfer the exact same code to a UIViewController class and add the UIWebView to the view, it works fine.
So does a UIWebView even work if it's not added to a view?
How can I add this with a zero frame or hidden from an NSObject class?
I've really cut down my code (below) which should work as it is but doesn't.
MyWebViewHelper.m
@interface MyWebViewHelper () <UIWebViewDelegate>
@property (strong) UIWebView *webview;
@end
- (instancetype)initWithURLString:(NSString *)urlString username:(NSString *)username password:(NSString *)password
{
if ((self = [super init])) {
}
return self;
}
- (void)readPage
{
NSLog(@"%s", __PRETTY_FUNCTION__);
self.webview=[[UIWebView alloc] init];
NSURL *url = [NSURL URLWithString:@"https://www.google.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
_webview.delegate = self;
[_webview loadRequest:requestObj];
}
#pragma mark - UIWebView Delegates
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"Should start loading: %@", [[request URL] absoluteString]);
NSLog(@"Headers: %@",[request allHTTPHeaderFields]);
NSLog(@"Data: %@", [[NSString alloc] initWithData:request.HTTPBody encoding:NSASCIIStringEncoding]);
NSLog(@"Method: %@",[request HTTPMethod]);
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"%s", __PRETTY_FUNCTION__);
NSLog(@"error:%@", error);
}
I've found the solution to this.
UIWebViewdoes in fact work without being added to a view. For some reason, myNSObjectclass running theUIWebViewwas being deallocated byARC. I only found this out when trying to get the class to add theUIWebViewto a view and it kept crashing but wouldn't give me any reasons or breakpoint.I eventually figured out to enable zombie objects and it complained about sending a message to a deallocated instance.
Anyway, the fix turned out to be adding a
strongproperty reference to my class to stop it being deallocated like this: