FSMountServerVolumeSync parameter objective c - objective-c

I'm just starting Objective C after being pampered with Applescript, and I can't seem to get FSMountServerVolumeSync to work. This is going to seem like a completely beginner question, but how do you pass a parameter from a variable to this action?
Let me explain:
I want to take a variable called *username and set it to the username in this action. I would also like to do this to *url and url. Is there any way someone could show me a sample of how to set this up, from an absolute beginner standpoint?
I am currently reading through tutorials and etc., but I would like to get this section of code done even if I don't exactly understand what I'm doing. ;)
Thanks in advance!
[edit] Here's what I've got so far:
- (IBAction)signin:(id)sender{
NSString * user = #"myusername";
NSString * password = #"mypassword";
NSURL * url = [NSURL URLWithString: #"smb://123.456.789.0"];
NSURL * mountDir = [NSURL URLWithString: #"/Students"];
OSStatus FSMountServerVolumeSync (
CFURLRef url,
CFURLRef mountDir,
CFStringRef user,
CFStringRef password,
FSVolumeRefNum *null,
OptionBits flags);
}

These aren't dumb questions at all.
Remember that CFStringRef and CFURLRef are toll free bridged, which means that the Objective C equivalents are NSString and NSURL. All you need to do is cast.
- (IBAction)signin:(id)sender{
NSString * user = #"myusername";
NSString * password = #"mypassword";
NSURL * url = [NSURL URLWithString: #"smb://123.456.789.0"];
NSURL * mountDir = [NSURL URLWithString: #"/Students"];
OptionBits flags = 0;
OSStatus err = FSMountServerVolumeSync (
(CFURLRef) url,
(CFURLRef) mountDir,
(CFStringRef) user,
(CFStringRef) password,
NULL,
flags);
if(err != noErr)
NSLog( #"some kind of error in FSMountServerVolumeSync - %ld", err );
}
See what I mean so far?
Here is some Apple documentation on toll free bridged types.

Related

Regular expression to validate a URL safe string in Objective C

In my iPhone application I am constructing a URL by passing some params
as in
NSURL * url;
url = [url URLByAppendingPathComponent:Param1];
Now I want to validate Param1 to accept only the URL safe characters, other way around is to encode the URL I agree , but I need to validate the Param1 since it is exposed to the user to change, is there any stright forward native API to do so?, or Regex is the only way? please provide me the Regex if so , Thanx in advance
You could encode it
NSString *encodedString = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)originalString,
NULL,
CFSTR(":/?#[]#!$&'()*+,;="),
kCFStringEncodingUTF8);
if (![encodedString isEqualToString:originalString]) {
// It contains characters that are probably not legal.
}
Or you could just check for the characters listed above, but what fun would that be? :-)
NSCharacterSet *charSet = [NSCharacterSet
characterSetWithCharactersInString:
#":/?#[]#!$&'()*+,;="];
NSRange range = [string rangeOfCharacterFromSet:charSet];
if (range.location != NSNotFound) { ... }

Objective-C URL encoding issues

I am creating a URL string like so:
[Items appendString:[object objectForKey:#"Items"]];
[Items appendString:#"*"];
[Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)];
//This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT
//add Items to URL
NSString *fullURL = [NSString stringWithFormat:#"https://example.com?Items=%#, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
but it returns like so:
Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT
how do I get it return like this:
%20%26%20 instead of %20&%20 for the & ?
I think the issue is that the method tries to be too clever - it only does as much as is necessary to get a legal URL and because you don't have a question mark in your string, it probably thinks it is OK to leave the ampersands in.
Try constructing the whole URL and do the escaping on the whole URL.
NSString *fullURL = [[#"https://example.com?Items=" stringByAppendingString: items]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Or perhaps use stringByAddingPercentEncodingWithAllowedCharacters:.
Try this.
fullURL=[fullURL stringByReplacingOccurrencesOfString:#"&" withString:#"%26"];
NSLog(#"fullURL: %# ...", fullURL);
Use CFURLCreateStringByAddingPercentEscapes() for getting UTF8stringencoding of characters
NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:#&=+$,/?%#[]"), kCFStringEncodingUTF8))

Persisting bookmark in core-data

I have an OSX application that is supposed to have a list of files from anywhere in the user's disk.
The first version of the app saves the path to these files in a core-data model.
However, if the file is moved or renamed, the tool loses its purpose and the app can crash.
So I decided to use bookmarks. It seems to be working, but every time I try to recover the data, I get the old path of the files. Why is that? What am I missing?
My core-data entity uses a binary data field to persist the bookmark.
The bookmark itself is done like this:
NSData * bookmark = [filePath bookmarkDataWithOptions:NSURLBookmarkCreationMinimalBookmark
includingResourceValuesForKeys:NULL
relativeToURL:NULL
error:NULL];
And on loading the application, I have a loop to iterate all the table and recover the bookmark like this:
while (object = [rowEnumerator nextObject]) {
NSError * error = noErr;
NSURL * bookmark = [NSURL URLByResolvingBookmarkData:[object fileBookmark]
options:NSURLBookmarkResolutionWithoutUI
relativeToURL:NULL
bookmarkDataIsStale:NO
error:&error];
if (error != noErr)
DDLogCError(#"%#", [error description]);
DDLogCInfo(#"File Path: %#", [bookmark fileReferenceURL]);
}
If I rename the file, the path is null. I see no difference between storing this NSData object and a string with the path. So I am obviously missing something.
Edit:
I also often get an error like this: CFURLSetTemporaryResourcePropertyForKey failed because it was passed this URL which has no scheme.
I appreciate any help, thanks!
I can't find any issues in my code, so I changed it.
After looking for the reason of the "no scheme" message, I came to the conclusion some third-party application is required for this code to work, and that's undesirable.
I am now using aliases. This is how I create them:
FSRef fsFile, fsOriginal;
AliasHandle aliasHandle;
NSString * fileOriginalPath = [[filePath absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
OSStatus status = FSPathMakeRef((unsigned char*)[fileOriginalPath cStringUsingEncoding: NSUTF8StringEncoding], &fsOriginal, NULL);
status = FSPathMakeRef((unsigned char*)[fileOriginalPath cStringUsingEncoding: NSUTF8StringEncoding], &fsFile, NULL);
OSErr err = FSNewAlias(&fsOriginal, &fsFile, &aliasHandle);
NSData * aliasData = [NSData dataWithBytes: *aliasHandle length: GetAliasSize(aliasHandle)];
And now I recover the path like this:
while (object = [rowEnumerator nextObject]) {
NSData * aliasData = [object fileBookmark];
NSUInteger aliasLen = [aliasData length];
if (aliasLen > 0) {
FSRef fsFile, fsOriginal;
AliasHandle aliasHandle;
OSErr err = PtrToHand([aliasData bytes], (Handle*)&aliasHandle, aliasLen);
Boolean changed;
err = FSResolveAlias(&fsOriginal, aliasHandle, &fsFile, &changed);
if (err == noErr) {
char pathC[2*1024];
OSStatus status = FSRefMakePath(&fsFile, (UInt8*) &pathC, sizeof(pathC));
NSAssert(status == 0, #"FSRefMakePath failed");
NSLog(#"%#", [NSString stringWithCString: pathC encoding: NSUTF8StringEncoding]);
} else {
NSLog(#"The file disappeared!");
}
} else {
NSLog(#"CardCollectionUserDefault was zero length");
}
}
However, I am still curious on why my previous code failed. I appreciate any thoughts on that. Thanks!

How to read input in Objective-C?

I am trying to write some simple code that searches two dictionaries for a string and prints to the console if the string appears in both dictionaries. I want the user to be able to input the string via the console, and then pass the string as a variable into a message. I was wondering how I could go about getting a string from the console and using it as the argument in the following method call.
[x rangeOfString:"the string goes here" options:NSCaseInsensitiveSearch];
I am unsure as to how to get the string from the user. Do I use scanf(), or fgets(), into a char and then convert it into a NSSstring, or simply scan into an NSString itself. I am then wondering how to pass that string as an argument. Please help:
Here is the code I have so far. I know it is not succinct, but I just want to get the job done:
#import <Foundation/Foundation.h>
#include <stdio.h>
#include "stdlib.h"
int main(int argc, const char* argv[]){
#autoreleasepool {
char *name[100];
printf("Please enter the name you wish to search for");
scanf("%s", *name);
NSString *name2 = [NSString stringWithFormat:#"%s" , *name];
NSString *nameString = [NSString stringWithContentsOfFile:#"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
NSString *dictionary = [NSString stringWithContentsOfFile:#"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];
NSArray *nameString2 = [nameString componentsSeparatedByString:#"\n"];
NSArray *dictionary2 = [dictionary componentsSeparatedByString:#"\n"];
int nsYES = 0;
int dictYES = 0;
for (NSString *n in nameString2) {
NSRange r = [n rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
nsYES = 1;
}
}
for (NSString *x in dictionary2) {
NSRange l = [x rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (l.location != NSNotFound){
dictYES = 1;
}
}
if (dictYES && nsYES){
NSLog(#"glen appears in both dictionaries");
}
}
}
Thanks.
Safely reading from standard input in an interactive manner in C is kind of involved. The standard functions require a fixed-size buffer, which means either some input will be too long (and corrupt your memory!) or you'll have to read in a loop. And unfortunately, Cocoa doesn't offer us a whole lot of help.
For reading standard input entirely (as in, if you're expecting an input file over standard input), there is NSFileHandle, which makes it pretty succinct. But for interactively reading and writing like you want to do here, you pretty much have to go with the linked answer for reading.
Once you have read some input into a C string, you can easily turn it into an NSString with, for example, +[NSString stringWithUTF8String:].

Is there a way to get the ip address from given url in Cocoa?

Given a URL like: https://dl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg,
how can I get the IP address, e.g., 74.125.224.140, in the Cocoa framework or with an Objective-C method?
try this. I think that is what you expecting.
It will convert string to url.
From this url you can get domain name.
From domain name you can get address as given below.
NSURL *validURL = [NSURL URLWithString: yourUrl];
NSString *host = [validURL host];
NSString *ipAdress = [[NSHost hostWithName:host]address];
Try this:
NSString *ip = [[NSHost hostWithName:(NSString *)yourDomainNameUrl] address];
This worked for me
#import <netdb.h>
#include <arpa/inet.h>
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
struct hostent *host_entry = gethostbyname(charUrl);
char *buff = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
});
Thanks to: source