Reputation: 10398
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);
}
Upvotes: 2
Views: 459
Reputation: 10398
I've found the solution to this. UIWebView
does in fact work without being added to a view. For some reason, my NSObject
class running the UIWebView
was being deallocated by ARC
.
I only found this out when trying to get the class to add the UIWebView
to 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 strong
property reference to my class to stop it being deallocated like this:
@property (strong, nonatomic) MyWebViewHelper *myWebHelper;
Upvotes: 5