-1

I would like to be able to upload a file using my FTP code and then be able to upload the file with a randomly generated name (preferable 7 characters long with just upper and lower case letters)

Here is my ftp method:

ftpManager = [[FTPManager alloc] init];
success = NO;
NSArray* serverData = nil;
FMServer* srv = [FMServer serverWithDestination:[@"IP" stringByAppendingPathComponent:@"/"] username:@"username" password:@"password"];
srv.port = self.portField.intValue;
switch (action) {
    case upload:
        success = [ftpManager uploadFile:fileURL toServer:srv];
        break;
    default;
        break;

How can I edit the file name that is uploaded to the ftp server?

EDIT: Added location of 'fileURL' code:

fileURL = [NSURL URLWithString:@"/tmp/tmpscr.png"];
    action = upload;
    [self runAction];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
CloudSync
  • 45
  • 12
  • 1
    Why `preferable 7 characters long with just upper and lower case letters` ? Why not a GUID, or a timestamp? – Wain Sep 15 '14 at 21:26
  • It is to match a current format as it is used to save images in a directory. So the file names are such as "DYGdsUs.png" – CloudSync Sep 15 '14 at 21:29
  • 1
    The "standard" approach is to use a timestamp. Eg, the UNIX "epoch" time in milliseconds. – Hot Licks Sep 15 '14 at 21:37
  • @HotLicks, that might be dangerous if names from different devices might collide. (though I am not sure if picking 7 letters out of 62 symbols is secure enough) – vikingosegundo Sep 15 '14 at 21:41
  • @vikingosegundo - Well the OP hasn't described the parameters of the problem at all, so we don't really know what kind of collisions (if any) need to be prevented. – Hot Licks Sep 15 '14 at 21:44
  • true, but if we should ask for clarification before we advertise a *standard* way. I'd say UUIDs would be the standard way. – vikingosegundo Sep 15 '14 at 21:46
  • Okay, let's back up a second. Where are these files being uploaded to, and by who/what? –  Sep 15 '14 at 22:07
  • possible duplicate of [Generate a random alphanumeric string in Cocoa](http://stackoverflow.com/q/2633801) – jscs Sep 16 '14 at 18:32

4 Answers4

1

I'd us a category on NSArray to shuffle like

@interface NSArray (RandomUtils)
-(NSArray *)arrayShuffled
@end


@implementation NSArray (RandomUtils)


-(NSArray *)arrayShuffled
{
    NSUInteger count = [self count];
    NSMutableArray *newArray = [NSMutableArray arrayWithArray:self];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) {
        NSUInteger nElements = count - index;
        NSUInteger n = (arc4random_uniform((u_int32_t)nElements)) + index;
        [newArray exchangeObjectAtIndex:index withObjectAtIndex:n];
    }];
    return newArray;
}
@end

and create the dire name like:

NSMutableArray *array = [@[] mutableCopy];

for (char i ='a'; i <='z'; ++i) {
    [array addObject:[NSString stringWithFormat:@"%c", i]];
}

for (char i ='A'; i <='Z'; ++i) {
    [array addObject:[NSString stringWithFormat:@"%c", i]];
}

for (int i = 0; i < 10; ++i) {
    [array addObject:[NSString stringWithFormat:@"%i", i]];
}


NSArray *shuffeldArray = [array arrayShuffled];

NSString* name = [[shuffeldArray subarrayWithRange:NSMakeRange(0, 7)] componentsJoinedByString:@""];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
1

I had a similar requirement, and wrote myself a class category on NSString that returns a random string of a given length:

Edit

Updated to use arc4random_uniform as suggested by @NoahWitherspoon

+ (NSString *)randomStringOfLength:(NSInteger)length {

    char str[length+1];

    for (int i=0; i<length; i++){

        char rand = randomChar();

        str[i]=rand;
    }

    str[length]='\0';

    return [NSString stringWithCString:str encoding:NSUTF8StringEncoding];
}

char randomChar(){

    char randomLower = 'a' + arc4random_uniform(26);
    char randomUpper = 'A' + arc4random_uniform(6);
    char randomNumber = '0' + arc4random_uniform(9);

    int randomVal = arc4random_uniform(100);

    char randomAlpha = (randomVal % 2 == 0) ? randomLower : randomUpper;

    //If you don't want a numeric as part of the string, just
    //return randomAlpha

    return (randomVal % 3 == 0) ? randomNumber : randomAlpha;
}
Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
ChrisH
  • 4,468
  • 2
  • 33
  • 42
  • I am using NSLog(@"%c", randomChar()); to print to the log but can you modify the code so it only returns a 7 long name with only upper and lower case letters? @ChrisH – CloudSync Sep 15 '14 at 22:09
  • 1
    `arc4random() % x` doesn’t give you a uniform distribution of values—you should be using `arc4random_uniform(x)` here. – Noah Witherspoon Sep 15 '14 at 22:23
  • @CloudSync see my updated answer. If you don't want alpha values in the random string, just return randomAlpha in the randomChar() function. If you want a string of 7 letters just call `[NSString randomStringOfLength:7]` – ChrisH Sep 16 '14 at 00:14
1

Here's what I'm usually using:

+ (NSURL*)randomFileURLInDocumentsFolder:(NSString*)folderName pathExtension:(NSString*)extension;{
NSString* folderPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:folderName];
// check if folder exists, else create
if (folderName && ![[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSURL* tmp = [NSURL fileURLWithPath:[folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%f%d.%@", [[NSDate date] timeIntervalSinceReferenceDate],arc4random()%1000, extension]]];
int count = 0;
while ([[NSFileManager defaultManager] fileExistsAtPath:[tmp path]]) {
    tmp = [NSURL fileURLWithPath:[folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%f%d.%@", [[NSDate date] timeIntervalSinceReferenceDate],arc4random()%1000, extension]]];
    count++;
}

return tmp;

}

Tim Specht
  • 3,068
  • 4
  • 28
  • 46
-1

I solved it in a very simplistic way and I will show you all for reference:

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

-(NSString *) randomStringWithLength: (int) len {

NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

for (int i=0; i<len; i++) {
    [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length]) % [letters length]]];     }

return randomString;
}

and then I used this method to generate a random mix with length len

NSString* myString = [self randomStringWithLength:7];

Hope this helped everyone!!!

CloudSync
  • 45
  • 12
  • This is a copy-paste of http://stackoverflow.com/a/2633948/ You must attribute your use of other people's work when posting on Stack Overflow. – jscs Sep 17 '14 at 18:34