NSRegularExpression not working - objective-c

I'm try to parse a photo id out of a facebook url, e.g.,
https://www.facebook.com/photo.php?fbid=267217740038587&set=a.207272412699787.48907.100002510899673&type=1
My regex is #"https?:\/\/(www\.)?facebook\.com\/photo\.php\?fbid=([0-9]+)"
I tested this with an external tool RegExhibit - http://homepage.mac.com/roger_jolly/software/ and it seems to work fine.
However it does not work in XCode. I tried to debug and the problem seems to be the \? after photo\.php. When I change it to
#"https?:\/\/(www\.)?facebook\.com\/photo\.php.fbid=([0-9]+)" (notice I change \? to .)
it works perfectly.
While this is acceptable I would like to know why \? doesn't work here. Any expert? :-)

I'm not sure, but perhaps the back slashes \ are escaping the relevant following character in the NSString itself when it is parsed. For instance,
NSLog(#"https?:\/\/(www\.)?facebook\.com\/photo\.php\?fbid=([0-9]+)");
actually prints https?://(www.)?facebook.com/photo.php?fbid=([0-9]+) which if then treated as its own regex would execute the way you describe it (and does execute semi-properly if you replace the ? with a .)
So, I'm guessing for it to work properly, you'd need #"https?:\\/\\/(www\\.)?facebook\\.com\\/photo\\.php\\?fbid=([0-9]+)" instead.

You can try this:
NSString *query = #"parameter=2&secondparameter=3"; // replace this with [url query];
NSArray *components = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
for (NSString *component in components) {
[parameters setObject:[[component componentsSeparatedByString:#"="] objectAtIndex:0] forKey:[[component componentsSeparatedByString:#"="] objectAtIndex:1]];
}

Related

escaping spaces in local url

i have the following code to try and load a local html page in a cocoa app...
NSString *basePath = #"file//Users/david/Documents/My Project/index.html";
NSString *escapedPath = [basePath stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL*url=[NSURL URLWithString:escapedPath];
NSURLRequest*request=[NSURLRequest requestWithURL:url];
NSLog(#"current file is %#", url);
Unfortunately, the url is always null, and if i look at the value of escapedPath i see '%20' escaping the space. however, this doesn't work in local. is there a stringBy function that escapes correctly for a local path?
Thanks!
For local paths you need to use fileURLWithPath:
See the docs here:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

Xcode HTTP GET Request

I am making an app in which you type a value into a textbox, and the app sends an HTTP GET request to my webserver, ie www.mywebserver.server.com/ihiuahdiuehfiuseh?' + textbox variable' However, I have no idea how to work with Xcode. I am experienced in basic PHP and HTML, and advanced C++, but I am so baffled by this Xcode stuff. In all other languages I have worked with, you could look up something like "how to play a sound file in (language)", and you will get something like "oh yeah just do play(mp3url). But, with Xcode, you have to initiate the connection, initiate the variables, etc etc. I bought 2 $30 books, but I am still so confused. So, back to the point, I just need the textbox numerical number to be parsed after the ? in the URl to be parsed as a variable.
This is an example of a non-http get synchronized
You can find more
-(void)aget:(NSString *)iurl{
NSURL*url = [NSURL URLWithString:iurl];
NSURLRequest *res = [NSURLRequest requestWithURL:url];
NSOperationQueue*que=[NSOperationQueue new];
[NSURLConnection sendAsynchronousRequest:res queue:que completionHandler:^(NSURLResponse*rep,NSData*data,NSError*err){
if ([data length]> 0 && err == nil) {
NSString* rel=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",rel);
}else{
NSLog(#"isnull");
}
}
];
}
Through this launch him
NSString * str = [self getDataFrom: # "your url"];
     NSLog (# "% #", str);
If you have a UITextFiled, you would do the following
NSString baseUrl = #"www.mywebserver.server.com/ihiuahdiuehfiuseh?"
NSString variable = textField.text;
NSString absoluteURL = [NSString stringWithFormat:#"%#%#", baseUrl, variable];
//Send the absolute variable now to the server
If you go for a solution like Omar Abdelhafith suggests, don't forget to url-encode your 'querystring'. There is a method in the string class for this: "stringByAddingPercentEscapesUsingEncoding", but it's not perfect.
I've recently used the solution suggested here: http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/.

NSTask Question

I'm trying to get my NSTask to unzip a file for me. This works fine if the path has no spaces, but when it does, it can't find any of the files. I can't hardcode the " signs because I'm storing the zip file in a temporary folder, which is assigned by the system.
Does anyone know how to achieve this?
Here's my code:
NSTask*task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/unzip"];
NSArray*arguments = [NSArray arrayWithObjects:zipPath,#"-d",path,nil];
[task setArguments:arguments];
[task launch];
[task release];
Why can't you embed the quote marks?
NSString *quotedPath = [NSString stringWithFormat:#"\"%#\"", path];
NSArray *arguments = [NSArray arrayWithObjects:zipPath, #"-d", quotedPath, nil];
Having a space in the argument does not look like your problem - note that the console is showing the pathname with a space. An argument with a space is passed as a single argument, I've just confirmed it will happily unzip #"a space.zip". Have you checked the file does exist where you think it does and you have access to it?
Could you parse the path components using NSString's - (NSArray *)pathComponents method, add the quotes where needed, then rebuild the string using (NSString *)pathWithComponents:(NSArray *)components
Does that work?

NSURL fileURLWithPath where NSString has a space

I've looked at quite a few of the related questions and cannot find a similar problem or a solution so my apologies if there is a duplicate out there somewhere.
Anyway, I'm trying to generate a file's NSURL to use with an NSXMLDocument. I have the following components:
const NSString * PROJECT_DIR = #"~/SP\\ BB/";
const NSString * STRINGS_FILE = #"Localizable.strings";
and construct the URL like so:
NSURL * stringsURL = [NSURL fileURLWithPath:[[NSString stringWithFormat:#"%#%#",PROJECT_DIR,STRINGS_FILE] stringByExpandingTildeInPath]];
however, the resulting path in the NSURL is:
file://localhost/Users/timothyborrowdale/SP2B/Localizable.strings
I have tried changing the PROJECT_DIR to
#"~/SP BB/"
#"~/SP\\\\ BB/" (changes to SP엀2B)
#"~/SP%20BB/"
#"~/SP\%20BB/"
with the same problem. I also tried typing out the file url completely and using [NSURL URLWithString:]
I have also tried using stringByAddingPercentEscapesUsingEncoding with both NSUTF8Encoding and NSASCCIEncoding and these have the same issue.
The NSString displays properly before being passed to NSURL or stringByAddingPercentEscapesUsingEncoding but has the problem once outputted from either.
Try this:
NSString *fnam = [#"Localizable" stringByAppendingPathExtension:#"strings"];
NSArray *parts = [NSArray arrayWithPathComponents:#"~", #"SP BB", fnam, (void *)nil];
NSString *path = [[NSString pathWithComponents:parts] stringByStandardizingPath];
NSURL *furl = [NSURL fileURLWithPath:path];
Foundation has a host of platform-independent, path-related methods. Prefer those over hard-coding path extension separators (often ".") and path component separators (often "/" or "\").
Try abandoning stringWithFormat: (never the right answer for stapling paths together) and stringByExpandingTildeInPath and using NSHomeDirectory() and stringByAppendingPathComponent: instead.
#"~/SP\\ BB/" (changes to SP엀2B)
How did you arrive at that conclusion?

How to use NSWorkspace launchApplicationAtURL?

I tried to run equivalent of "TextMate foo.txt" using launchApplicationAtURL. The name of binary is "TextMate", and I have one parameter.
I tried the following code, but it doesn't seem to work.
// find the textmate
NSURL * bURL = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:#"com.macromates.textmate"];
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
// find the parameter
NSString * f = #"foo.txt";
NSArray * myArray2 = [NSArray arrayWithObjects:f,nil];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:myArray2 forKey:NSWorkspaceLaunchConfigurationArguments];
[ws launchApplicationAtURL:bURL options:NSWorkspaceLaunchDefault configuration:dict error:nil];
What's wrong with this?
Added
I checked this code actually works, I got something wrong with how 'TextMate.app' deals with the parameters.
Most apps don't use command line parameters. If you want to open a particular file with a particular app, use -[NSWorkspace openFile:withApplication:].