Send a response from AFHTTPRequestOperation to UIWebview

My code makes two requests to the server. One in uiwebview directly and one with AFHTTPRequestOperation. I would like to use AFHTTPRequestOperation and just pass the response to my uiwebview. What is the correct syntax for passing a response to uiwebview, and not for downloading it? How can I do this without a double call from the server? I still want to check the success or failure of the download request, and also send the username and password to connect to the URL.

- (BOOL)textFieldShouldReturn:(UITextField *)textField { [itemField resignFirstResponder]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *userName = [defaults objectForKey:@"storedUserName"]; NSString *passWord = [defaults objectForKey:@"storedPassWord"]; NSURL *url = [NSURL URLWithString:@"http://www.example.net/"]; AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url]; [client setAuthorizationHeaderWithUsername:userName password:passWord]; NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:[@"/example/itemlookup.php?item=" stringByAppendingString:itemField.text] parameters:nil]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { //calling again here was the only way I could figure out to get this into my webview //need to get response from above and put into the uiwebview [webView loadRequest:request]; NSLog(@"Success"); } failure: ^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Failure"); }]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation]; return YES; } 
+4
source share
2 answers

I would recommend using the AFNetworking UIWebView category, which does just that; uses AFHTTPRequestOperation to load the contents of a web page, and then loads it into a web view as an HTML string.

Otherwise, I would recommend looking at the category to see if you can adapt your code for your use. https://github.com/AFNetworking/AFNetworking/blob/master/UIKit%2BAFNetworking/UIWebView%2BAFNetworking.m

+1
source

If this URL returns HTML, you can use the download method (HTTML): (NSString *) baseURUR: (NSURL *) baseURL for the UIWebView.

Sort of:

 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { [webView loadHTMLString:responseObject baseURL:url]; //If responseObject is HTML NSLog(@"Success"); } failure: ^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Failure"); }]; 

The only thing that can change is the response object. Perhaps you are not getting a string, but NSURLResponse or something like that.

0
source

All Articles