Can't show the right URL in my iPad simulator - objective-c

I'm building an iPad app and that's a browser. I have a little problem because in a text field, I can write any web direction, such http://www.google.com/. The problem is that when I change the page, at, for example, http://www.apple.com/ , it stills says google. I have written the code, but I don't know why it doesn't work!
-(void)currentURL{
int i= 0;
while (i == 0) {
url = [request URL];
NSLog(#"%#", url.absoluteString);
textfield.text = url.absoluteString;
}}
Please I need some help!

replace this:
textfield.text = url.absoluteString;
with this:
if(textfield)
{
if(url)
{
textfield.text = [url absoluteString];
} else {
NSLog( #"my request or URL is nil");
}
} else {
NSLog( #"I didn't set my textfield");
}

You need to implement the web view delegate which will tell you when the page inside the web view changes, e.g. when the user clicks a link. You can then use the delegate methods to update your text field to the new URL.
if you've done that and your textfield isn't updating, you've probably forgotten to connect your textfield in your nib file to the textfield outlet of your class, so your self.textfield property is nil and setting its text does nothing.

Related

OS X - WebView questions

I am using webview in one of OS X app and got strange requirement from client that:
1) Need to show address bar in app for webview, I tried if there's any support by webview but couldn't really find. I know I can do that by having a text field and show URL in that but I am not sure if that's the right way so is there any other better way, please suggest.
2) Need to also check whether loaded URL has SSL support and show some icon like padlock (open/close). So again is there any support or feature of Webview that i can use or I just have to check for URL prefix of http or https? Please help.
Thanks in advance.
MP
That is exactly what you should do. Create the text field, and insert this bit of code into your application:
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:#"window.location"];
[myTextField setStringValue:currentURL];
}
For the second part of your question, use the currentURL string, and check if https:// exists in the string using the NSNotFound method. By using [myString rangeOfString:#"string_to_search_for"].location != NSNotFound, it will return true if the rangeOfString: is found. (!= means not equal to.) (So != NSNotFound means that your rangeOfString is not equal to not being found... if that makes sense)
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:#"window.location"];
if ([currentURL rangeOfString:#"https://"].location != NSNotFound) {
// *https://* exists! Show your closed padlock image!
} else {
// *https://* does not exist. Show your open padlock image.
}
}
Hope this was helpful!

How to clear username and password on CocoaLibSpotify logout?

I'm using the CocoaLibSpotify library to develop an iOS application that will utilize the Spotify API. I've got it just about where I want it, but I've run into a bit of a problem.
When the user touches my "Logout of Spotify" button, I execute the following code:
-(IBAction)logoutButtonTouched:(id)sender
{
// Clear out the user's settings that I am saving.
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[SPSession sharedSession] logout:^(void) {
SPLoginViewController *controller = [SPLoginViewController loginControllerForSession:[SPSession sharedSession]];
controller.allowsCancel = NO;
}];
}
This does indeed logout the user and display the SPLoginViewController, but my problem is, the username and password field still contain the values that they'd logged-in with. Does anyone know of a way to clear these fields when I display the SPLoginViewController?
This functionality isn't in the login controller, which is indeed a bug.
You can do it like this. Please note that this is really fragile code and will fail if any internal detail of the login controller changes, and it will in the future:
SPLoginViewController *controller = [SPLoginViewController loginControllerForSession:[SPSession sharedSession]];
id internalLoginViewController = [controller.viewControllers objectAtIndex:0];
UITextField *loginField = [internalLoginViewController valueForKey:#"usernameField"];
UITextField *passwordField = [internalLoginViewController valueForKey:#"passwordField"];
loginField.text = #"";
passwordField.text = #"";

UISwitches, need an explanation

How do the switches work in XCode4? how do i check which properties are available to me for the switches?
i am trying to check the state of a switch and make a label change according to the state. Something like this:
-(IBAction)clickedOnSwitch:(id)sender {
NSString *switchState = [[NSString alloc]init];
if (mySwitchIsOn) {
switchState = #"switch is On";
}
else
{
switchState = #"switch is Off";
}
myLabel.text = switchState;
[switchState release];
}
Take a look at the UISwitch class reference either on the web or in the Xcode documentation browser.

Adding QLPreviewController as subview doesn't load PDF

I'm trying to add a QLPreviewController's view as a subview (no--I cannot use a nav controller or modal). It only shows the fabric background of the QLPreviewController.
I create one and add it as a subview:
QLPreviewController* preview = [[[QLPreviewController alloc] init] autorelease];
preview.dataSource = self;
preview.delegate = self;
preview.view.frame = CGRectMake(0, 0, self.pdfPreviewView.frame.size.width, self.pdfPreviewView.frame.size.height);
self.pdfPreviewView.previewController = preview;
[self.pdfPreviewView addSubview:preview.view];
[preview reloadData];
My QLPreviewControllerDataSource methods work fine (viewing 1 pdf at a time):
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index
{
NSString *path = [[ResourceManager defaultManager] pathForPDF:self.currentPDF];
NSURL *url = [NSURL fileURLWithPath:path];
if ([QLPreviewController canPreviewItem:url]) {
return url; // This always returns
}
return nil; // This line is never executed
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
return 1;
}
The data source method always returns the file url, and QLPreviewController says it can open the file, but it never actually does. I just get the background. The self.currentPDF is set before I create the QLPreviewController and does contain the correct information (from CoreData).
The delegate methods never get called. But I'm also not using it in a standard way, so that's not totally unexpected.
I've also tried calling [preview setNeedsLayout], [preview setNeedsDisplay'], and [preview refreshCurrentPreviewItem] but those just call the data source methods and don't change anything.
The PDFs are valid. I can open them in both Xcode and Preview, so that's not the problem. I'm kind of stumped as to why this won't work. Any help would be appreciated in getting this to work.
Turns out I was sending QLPreviewController the wrong path. It wasn't finding the PDF in the bundle correctly. I needed to use pathForResource:ofType:inDirectory.

Detecting Download in UIWebView

I have a programatically crated UIWebView, and it is used to browse a iPhone-style site stored on my server. In this website, there are a few links to files users can download into my application. Right now, I'm trying to detect this with:
- (BOOL) webView:(UIWebView *) webView shouldStartLoadWithRequest:(NSURLRequest *) request navigationType:(UIWebViewNavigationType) navigationType
{
url = [request URL];
NSString *mimeType = [request valueForHTTPHeaderField:#"Content-Type"];
NSLog(#"Content-type: %#", mimeType);
if(mimeType == #"application/zip" || mimeType == #"application/x-zip" || mimeType == #"application/octet-stream")
{
NSLog(#"Downloading file!");
[NSThread detachNewThreadSelector:#selector(download:) toTarget:self withObject:#"/tmp/file.ipa"];
return NO;
}
return YES;
}
However, when this method is called, the content-type header is almost always (null), so I never am able to download a file.
How would you do this correctly?
You're trying to detect a Content-Type from an NSURLRequest which has not yet been made. You won't know the Content-Type until after the request is made using NSURLConnection. In this case, I'd probably just look at the file extension of the URL path.
----------Swift 4+-------
Example for audio/mp3 detect -
Step 1: Use delegate
class ViewController : WKUIDelegate,WKNavigationDelegate {
Step 2: Setting WebKit
func setWebView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
let myURL = URL(string: "https://www.bossmobi.guru/files/download/type/320/id/197255")//your audio url
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
Step 3: Get audio MIME type from webkit delegate.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: #escaping (WKNavigationResponsePolicy) -> Void) {
print( #function + "url is \(String(describing: webView.url))" + "Mimetype" + "\(navigationResponse.response.mimeType ?? "NotAvailable")")
if let _ = navigationResponse.response.mimeType?.range(of: "audio/mpeg") {
print("MP3 is audio url \(String(describing: webView.url))")
webView.stopLoading()
}
decisionHandler(.allow)
}
---------ObjC----------
WKWebView setup
NSString *urlString = #"https://www.bossmobi.guru/files/download/type/320/id/197255";
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *_demoWKWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
_demoWKWebView.navigationDelegate = self;
_demoWKWebView.UIDelegate = self;
NSURL *nsurl=[NSURL URLWithString:urlString];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[_demoWKWebView loadRequest:nsrequest];
[self.view addSubview:_demoWKWebView];
WKWebView delegate
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//NSLog(#"decidePolicyForNavigation---Response %#",webView.URL);
if ([navigationResponse.response.MIMEType isEqualToString:#"audio/mpeg"]) {
NSLog(#"MP3 audio url is %#",webView.URL);
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
So here's the problem: UIWebView doesn't download anything it can't display, and it doesn't know how to display a ZIP file. It will always fail before the Content-Type is filled in.
So, what to do? I don't know if your server-side app runs on more than the iPhone, but you could register a custom URL scheme with links like myapplication://example.com/stuff/yourhexurlgoeshere. You can create a custom URL handler for the myapplication scheme. A couple of seconds of Googling produced this site, which explains how to do it.
This has an additional benefit because if you, say, emailed such a link to another user, they could tap on it in Mail and have it open in your application.