NSURL with http:// works fine but with ftp:// not - objective-c

NSString *adress = [NSString stringWithFormat:#"ftp://%#:%##%#/%#x050-pegel.txt", benutzer.text, passwort.text, server.text, pfad.text];
NSURL *aURL = [[NSURL alloc]initWithString:adress];
NSString *theData = [NSString stringWithContentsOfURL:aURL];
textview.text = theData;
can some one help me please ?

AFAIK, FTP support is not part of the Cocoa frameworks. You could get more information by using +[NSString stringWithContentsOfURL:encoding:error:] and looking at the NSError object, like so:
NSError *error = nil;
NSString *theData = [NSString stringWithContentsOfURL:aURL encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"received error: %#", error);
}
A quick google search for "cocoa ftp" shows that there are several approaches to connecting to an FTP server from Objective-C.

Related

Json deserialization with objective-c failing on copyright symbol

I'm primarily a c# developer but I have been tasked with resolving a bug in an objective-c mac client. I am using nsjsonserialization to serialize the json object.
The bug occurs on deserialization if the json object contains the copyright symbol.
We were using sbjson and I switched to nsjsonserialization and that didn't resolve the issue. I don't know if I am doing it wrong or if I need to use a different serialization library. In c# I could just use newtonsoft. Is there a similarly standard json serialization library for objective-c that I should use?
Here is the serialization code:
-(void)sendMessage:(NSString *)method:(NSDictionary *)inData {
NSDictionary *outData = [[NSDictionary alloc] init];
#try {
JsonServiceComm *newCom = [[JsonServiceComm alloc] init];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", host, method]];
NSData *json = [NSJSONSerialization dataWithJSONObject:inData options:kNilOptions error:nil];
json = [json subdataWithRange:NSMakeRange(0, [json length] - 1)];
NSString* jsData = [NSString stringWithUTF8String:[json bytes]];
NSString *outData = [newCom userSpaceRequest:url :jsData];
} #catch (NSException* ex) {
NSLog(#"%#", [ex reason]);
}
}
Here is where it is being deserialized:
-(void)handleMessage:(NSString *)messageType message:(NSString *)message {
#autoreleasepool {
NSData *jsMessage = [message dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsMessage options:NSJSONReadingMutableLeaves error:&error];
}}
If the data does not contain a copyright symbol, *data is populated with a dictionary of values, however if it does contain the copyright symbol, *data comes out nil. The error returned is "Unexpected end of file while parsing object."
This is resolved. I discovered that the json was being passed through a separate json parser where it was not being utf8 encoded.
Try using options:0 instead of options:NSJSONReadingMutableLeaves
https://developer.apple.com/documentation/foundation/nsjsonreadingoptions/nsjsonreadingmutableleaves?language=objc

Using Objective-c to parse information from JSON url

I'm trying to write a piece of code that will make use of reddits JSON format. I intend to visit the url: http://www.reddit.com/r/pics/new/.json, search for the string: "title": " and write everything from there till the next apostrophe " to the log, continuing until all titles have been written to the log.
So far I have this, but I am not getting any log output. Can anybody help me?
- (void)viewDidLoad
{
NSString *redditString = #"http://www.reddit.com/r/pics/new/.json";
NSURL *redditURL = [NSURL URLWithString:redditString];
NSError *error;
NSCharacterSet *commaSet;
NSScanner *theScanner;
NSMutableString *jsonText = [[NSMutableString alloc] init];
NSString *TITLE = #"\"title\": \"";
NSString *postTitle;
commaSet = [NSCharacterSet characterSetWithCharactersInString:#"\""];
theScanner = [NSScanner scannerWithString:jsonText];
[jsonText appendString:[NSString stringWithContentsOfURL:redditURL encoding:NSASCIIStringEncoding error:&error]];
if ([theScanner scanString:TITLE intoString:NULL] && [theScanner scanUpToCharactersFromSet:commaSet intoString:&postTitle] && [theScanner scanString:#"\"" intoString:NULL]) {
NSLog(#"%#", postTitle);
}
}
Oh, and this all builds with no errors, but that's no surprise.
Thanks very much for your help, all tips, corrections, or anything else very much appreciated.
NSScanner is the wrong tool for the job. You'd better use a JSON (de)serializer, such as NSJSONSerialization, instead.
To make your life even easier you can take advantage of AFNetworking, a networking framework which supports JSON requests. Your code would reduce to something like
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://www.reddit.com/r/pics/new/.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *entries = responseObject[#"data"][#"children"];
for (NSDictionary *entry in entries) {
NSLog(#"%#", entry[#"title"]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Obj C Reading Files, txt file not found

I'm trying to read information from a text file in an Obj. C program and whenever I try to NSLog the output, I'm getting (null). I've made sure that the text files I'm working with are in my Copy Bundle Resources, which is what all of the other answers I've found have suggested. I'm using the following to access the files:
NSString *rightsPath = [[NSBundle mainBundle] pathForResource:#"Sample Maze Rights" ofType:#"txt"];
NSString *rightsContent = [NSString stringWithContentsOfFile:rightsPath encoding:NSUTF8StringEncoding error:NULL];
Can anyone make any suggestions?
That's what error argument is for.
NSError *error = nil;
NSString *rightsContent = [NSString stringWithContentsOfFile:rightsPath
encoding:NSUTF8StringEncoding
error:&error];
if (rightsContent == nil)
NSLog(#"error: %#", [error description]);

Renaming an existing file with Obj-C

I've seen this question asked a few times but I have been unable thus far to achieve success using any of the post solutions. What I am trying to do is rename a file in the local storage of an app (also kind of new to Obj-c). I am able to retrieve the old path and create the new path, but what would I have to write in order to actually change the files name?
What I have thus far is:
- (void) setPDFName:(NSString*)name{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* initPath = [NSString stringWithFormat:#"%#/%#",[dirPaths objectAtIndex:0], #"newPDF.pdf"];
NSString *newPath = [[NSString stringWithFormat:#"%#/%#",
[initPath stringByDeletingLastPathComponent], name]
stringByAppendingPathExtension:[initPath pathExtension]];
}
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
The code is very messy; try this:
- (BOOL)renameFileFrom:(NSString*)oldName to:(NSString *)newName
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *oldPath = [documentDir stringByAppendingPathComponent:oldName];
NSString *newPath = [documentDir stringByAppendingPathComponent:newName];
NSFileManager *fileMan = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileMan moveItemAtPath:oldPath toPath:newPath error:&error])
{
NSLog(#"Failed to move '%#' to '%#': %#", oldPath, newPath, [error localizedDescription]);
return NO;
}
return YES;
}
and call this using:
if (![self renameFileFrom:#"oldName.pdf" to:#"newName.pdf])
{
// Something went wrong
}
Better still, put the renameFileFrom:to: method into a utility class and make it a class method so it can be called from anywhere in your project.

OSX Application, get file data that user selected using NSOpenPanel

I am new to developing OSX Applications. I normally do iOS Apps, so alot of the concepts carry over. However, I cannot quite seem to figure out why I cannot retrieve the data of a file on my system.
Is there something that needs to be done first in order to read files on the users system?
Here is what I have:
- (IBAction)btnBrowse:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
//Get the file url user selected
NSURL *file = [[panel URLs] objectAtIndex:0];
//Get the file data
NSError *error;
NSString *fileData = [NSString stringWithContentsOfFile:[NSString stringWithFormat:#"%#", file] encoding:NSUTF8StringEncoding error:&error];
//This returns null
NSLog(#"%#", fileData);
//This says that the file does not exist
NSLog(#"Error: %#", error.localizedDescription);
}
}];
}
NSOpenPanel returns NSURL objects, the easiest solution is to use the NSURL related API
NSString *fileData = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];
If you don't know the text encoding you could use this API, if the reading succeeds, encoding contains the used encoding.
NSStringEncoding encoding;
NSString *fileData = [NSString stringWithContentsOfURL:file usedEncoding:&encoding error:&error];
Use the -[NSURL path] method instead of calling 'file' directly, as it's a NSURL, not NSString.