UIWebView not opening a link - objective-c

for(int i=0; i<arrString.count;i++){
if([[arrString objectAtIndex:i] rangeOfString:#"www."].location != NSNotFound)
link = [arrString objectAtIndex:i];
}
NSString *url = (#"THIS IS WHERE HTTP:// would Be!%#", link);
NSLog(#"THIS IS WHERE HTTP:// would Be!%#", url);
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[_webView1 loadRequest:nsrequest];
When I use NSLog:
NSLog(#"THIS IS WHERE HTTP:// would Be!, url);
It logs the correct URL that begins with http://. However, when I set the string URL equal to http://"link", it returns nothing. Any help is much appreciated.
(Stack Overflow is not letting me put the real HTTP:// followed by an %#.)

It looks like you may need to use stringWithFormat:
NSString *domainName = #"aol.com";
NSString *url = [NSString stringWithFormat:#"http://www.%#", domainName];

Related

Google directions' URL returning "ZERO RESULTS"

I've followed this tutorial - https://www.youtube.com/watch?v=AdV7bCWuDYg
Trying to draw route on map and I do successfully send latitude/longitude of origin/destination. The problem is its generated URL.
I keep getting this
http://maps.googleapis.com/maps/api/directions/json?&origin=37.661519,127.061106&destination=37.664185,127.062994&sensor=false
But as far as I know, the URL should end with |45.566346,18.667512 something like that. I don't know what I'm doing wrong because the tutorial claims it works and its by Google I think.
- (void)setDirectionsQuery:(NSDictionary *)query withSelector:(SEL)selector
withDelegate:(id)delegate{
NSArray *waypoints = [query objectForKey:#"waypoints"];
NSLog(#"***waypoints : %#", waypoints);
NSString *origin = [waypoints objectAtIndex:0];
int waypointCount = [waypoints count];
int destinationPos = waypointCount -1;
NSString *destination = [waypoints objectAtIndex:destinationPos];
NSString *sensor = [query objectForKey:#"sensor"];
NSMutableString *url =
[NSMutableString stringWithFormat:#"%#&origin=%#&destination=%#&sensor=%#",
kMDDirectionsURL,origin,destination, sensor];
if(waypointCount>2) {
[url appendString:#"&waypoints=optimize:true"];
int wpCount = waypointCount-2;
for(int i=1;i<wpCount;i++){
[url appendString: #"|"];
[url appendString:[waypoints objectAtIndex:i]];
}
}
url = [[url
stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]mutableCopy];
_directionsURL = [NSURL URLWithString:url];
NSLog(#"url : %#", url);
[self retrieveDirections:selector withDelegate:delegate];}
After hours of research I've noticed on Google Directions page that the required URL format is a little different from the one I've been using but still no luck.
[NSMutableString stringWithFormat:#"%#origin=%#&destination=%#&key=[my api key],
kMDDirectionsURL,origin,destination];
Your url should work, I changed the origin to San Francisco and destination to Mountain View and it works:
http://maps.googleapis.com/maps/api/directions/json?&origin=san+francisco&destination=mountain+view&sensor=false
It is possible that Google Maps does not know how to get from 37.661519,127.061106 to 37.664185,127.062994

How to get an NSURL part without query string? [duplicate]

What's the best way to get an url minus its query string in Objective-C? An example:
Input:
http://www.example.com/folder/page.htm?param1=value1&param2=value2
Output:
http://www.example.com/folder/page.htm
Is there a NSURL method to do this that I'm missing?
Since iOS 8/OS X 10.9, there is an easier way to do this with NSURLComponents.
NSURL *url = [NSURL URLWithString:#"http://hostname.com/path?key=value"];
NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
urlComponents.query = nil; // Strip out query parameters.
NSLog(#"Result: %#", urlComponents.string); // Should print http://hostname.com/path
There's no NSURL method I can see. You might try something like:
NSURL *newURL = [[NSURL alloc] initWithScheme:[url scheme]
host:[url host]
path:[url path]];
Testing looks good:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:#"http://www.abc.com/foo/bar.cgi?a=1&b=2"];
NSURL *newURL = [[[NSURL alloc] initWithScheme:[url scheme]
host:[url host]
path:[url path]] autorelease];
NSLog(#"\n%# --> %#", url, newURL);
[arp release];
return 0;
}
Running this produces:
$ gcc -lobjc -framework Foundation -std=c99 test.m ; ./a.out
2010-11-25 09:20:32.189 a.out[36068:903]
http://www.abc.com/foo/bar.cgi?a=1&b=2 --> http://www.abc.com/foo/bar.cgi
Here is the Swift version of Andree's answer, with some extra flavour -
extension NSURL {
func absoluteStringByTrimmingQuery() -> String? {
if var urlcomponents = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) {
urlcomponents.query = nil
return urlcomponents.string
}
return nil
}
}
You can call it like -
let urlMinusQueryString = url.absoluteStringByTrimmingQuery()
Swift Version
extension URL {
func absoluteStringByTrimmingQuery() -> String? {
if var urlcomponents = URLComponents(url: self, resolvingAgainstBaseURL: false) {
urlcomponents.query = nil
return urlcomponents.string
}
return nil
}
}
Hope this helps!
What you probably need is a combination of url's host and path components:
NSString *result = [[url host] stringByAppendingPathComponent:[url path]];
You could try using query of NSURL to get the parameters, then strip that value using stringByReplacingOccurrencesOfString of NSString?
NSURL *before = [NSURL URLWithString:#"http://www.example.com/folder/page.htm?param1=value1&param2=value2"];
NSString *after = [before.absoluteString stringByReplacingOccurrencesOfString:before.query withString:#""];
Note, the final URL will still end with ?, but you could easily strip that as well if needed.
I think -baseURL might do what you want.
If not, you can can do a round trip through NSString like so:
NSString *string = [myURL absoluteString];
NSString base = [[string componentsSeparatedByString:#"?"] objectAtIndex:0];
NSURL *trimmed = [NSURL URLWithString:base];
NSURL has a query property which contains everything after the ? in a GET url. So simply subtract that from the end of the absoluteString, and you've got the url without the query.
NSURL *originalURL = [NSURL URLWithString:#"https://winker#127.0.0.1:1000/file/path/?q=dogfood"];
NSString *strippedString = [originalURL absoluteString];
NSUInteger queryLength = [[originalURL query] length];
strippedString = (queryLength ? [strippedString substringToIndex:[strippedString length] - (queryLength + 1)] : strippedString);
NSLog(#"Output: %#", strippedString);
Logs:
Output: https://winker#127.0.0.1:1000/file/path/
The +1 is for the ? which is not part of query.
You might fancy the method replaceOccurrencesOfString:withString:options:range: of the NSMutableString class. I solved this by writing a category for NSURL:
#import <Foundation/Foundation.h>
#interface NSURL (StripQuery)
// Returns a new URL with the query stripped out.
// Note: If there is no query, returns a copy of this URL.
- (NSURL *)URLByStrippingQuery;
#end
#implementation NSURL (StripQuery)
- (NSURL *)URLByStrippingQuery
{
NSString *query = [self query];
// Simply copy if there was no query. (query is nil if URL has no '?',
// and equal to #"" if it has a '?' but no query after.)
if (!query || ![query length]) {
return [self copy];
}
NSMutableString *urlString = [NSMutableString stringWithString:[self absoluteString]];
[urlString replaceOccurrencesOfString:query
withString:#""
options:NSBackwardsSearch
range:NSMakeRange(0, [urlString length])];
return [NSURL URLWithString:urlString];
}
#end
This way, I can send this message to existing NSURL objects and have a new NSURL object be returned to me.
I tested it using this code:
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSURL *url = [NSURL URLWithString:#"http://www.example.com/script.php?key1=val1&key2=val2"];
// NSURL *url = [NSURL URLWithString:#"http://www.example.com/script.php?"];
// NSURL *url = [NSURL URLWithString:#"http://www.example.com/script.php"];
NSURL *newURL = [url URLByStrippingQuery];
NSLog(#"Original URL: \"%#\"\n", [url absoluteString]);
NSLog(#"Stripped URL: \"%#\"\n", [newURL absoluteString]);
}
return 0;
}
and I got the following output (minus the time stamps):
Original URL: "http://www.example.com/script.php?key1=val1&key2=val2"
Stripped URL: "http://www.example.com/script.php?"
Note that the question mark ('?') still remains. I will leave it up to the reader to remove it in a secure way.
We should try to use NSURLComponents
NSURL *url = #"http://example.com/test";
NSURLComponents *comps = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:YES];
NSString *cleanUrl = [NSString stringWithFormat:#"%#://%#",comps.scheme,comps.host];
if(comps.path.length > 0){
cleanUrl = [NSString stringWithFormat:#"%#/%#",cleanUrl,comps.path];
}
I think what you're looking for is baseUrl.

Parsing NSURL in Objective-C

I have an NSTextView control that could potentially have links in it. How do I get the full url of the link?
Here is what I have so far
-(BOOL)textView:(NSTextView *)aTextView clickedOnLink:(id)aLink atIndex:(NSUInteger)charIndex
{
NSURL *htmlURL = [NSURL fileURLWithPathComponents:[aLink pathComponents]];
}
This gives me a URL that begins with file://localhost ... How do I get rid of that portion of the URL?
NSURL* url = [NSURL URLWithString:#"http://localhost/myweb/index.html"];
NSString* reducedUrl = [NSString stringWithFormat:
#"%#://%#",
url.scheme,
[url.pathComponents objectAtIndex:1]];

Drag&Drop NSURL without "file://"

I'm implementing my drag&drop method. I need that when user drags something on my app window I can get that file URL. NSURL needs to be converted to char. Thats OK. But how to remove file:// from url? My current code:
pboard = [sender draggingPasteboard];
NSString *url = [[NSURL URLFromPasteboard:pboard] absoluteString];
input_imageN = strdup([url UTF8String]);
its OK, but it gives url with file:// prefix. I tried using
NSURL *fileUrl = [[NSURL URLFromPasteboard:pboard] isFileURL];
NSString *url = [fileUrl absoluteString];
NSLog(#"url: %#", [NSURL URLFromPasteboard:pboard]);
input_imageN = strdup([url UTF8String]);
but it says that
Cannot initialize a variable of type 'NSURL *' with an rvalue of type 'BOOL' (aka 'signed char')
at
NSURL *fileUrl = [[NSURL URLFromPasteboard:pboard] isFileURL];
To go from a file URL to the path as a C string in the appropriate representation for the filesystem, you'd do:
NSURL *fileURL = [NSURL URLFromPasteboard: pboard];
NSString *filePath = [fileURL path];
char *filesystemRepresentation = [filePath filesystemRepresentation];
This avoids assumptions that stripping off the scheme leaves you with just the path, or that the filesystem is definitely happy accepting UTF8-encoded paths.
url = [url stringByReplacingOccurencesOfString:#"file://" withString:#""];
Hope this helps. Cheers!
#user23743's answer is correct. Since iOS 7 though NSURL has its own filestSystemRepresentation method.
In Swift:
if let fileURL = NSURL(fromPasteboard: pboard) {
let representation = fileURL.fileSystemRepresentation
}
if let fileURL = NSURL(from: pboard)?.filePathURL {
}
has been most effective for me.

Problem in converting urlString into NSURL in iphone sdk

I am having string at first the method calls with timestamp value nil and I am getting converted the string into url .next time when I click load more results button again the method calls with time stamp value assigned to it.but the url string is not converting into NSURL iam getting the null value into it.
-(NSMutableArray*)getTextMessagesArray:(NSString *)endTimestamp
{
printf("\n endtimestamp value...%s",[endTimestamp UTF8String]);
NSString *urlString = #"http://123.237.186.221:8080/upload/textRequest.jsp";
urlString = [urlString stringByAppendingString:#"?beginTimestamp="];
urlString = [urlString stringByAppendingString:#"&endTimestamp="];
if([endTimestamp length]>0)
{
urlString = [urlString stringByAppendingString:endTimestamp];
}
printf("\n &*(*(((urlString...%s",[urlString UTF8String]);
NSURL* aUrl = [NSURL URLWithString:urlString];
NSLog(#"url in appdelegaare in text...%#",aUrl);
[textParser parseXMLFileAtURL:aUrl];
textMessagesList = [textParser getTextMessagesList];
printf("\n textMessagesList Count in appDelegate....%d",[textMessagesList count]);
return textMessagesList;
}
The result I am getting in console is:
&*(*(((urlString...http://123.237.186.221:8080/upload/textRequest.jsp?endTimestamp=2010-10-08 16:20:47.0
url in appdelegaare in text...(null)
Guy's can any one suggest me why this happening
Anyone's help will be much appreciated.
Thanks to all,
Monish.
Your problem is that valid URLs cannot contains spaces. You want to do something along the following lines:
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// escapedUrlString should be "http://123.237.186.221:8080/upload/textRequest.jsp?endTimestamp=2010-10-08%2016:20:47.0"
NSURL *aUrl = [NSURL URLWithString:escapedUrlString];
This might be what you wanted.