Concatenating Objective-C NSStrings - iphone

I'm a total newbie at Objective-C, so bear with me. This is how I'm concatenating my URL:
id url = [NSURL URLWithString:#"http://blahblah.com/gradient.jpg"];
id image = [[NSImage alloc] initWithContentsOfURL:url];
id tiff = [image TIFFRepresentation];
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent: #"Desktop"];
NSString *fileToWrite = #"/test.tiff";
NSString *fullPath = [docsDir stringByAppendingString:fileToWrite];
[tiff writeToFile:fullPath atomically:YES];
It works, but it seems sloppy. Is this the ideal way of doing concatenating NSStrings?

stringByAppendingString: or stringWithFormat: pretty much is the way.

You can append multiple path components at once. E.g.:
NSString* fullPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Desktop/test.tiff"];
You can also specify the entire path in a single string:
NSString* fullPath = [#"~/Desktop/test.tiff" stringByExpandingTildeInPath];

Have you looked into NSMutableString ?

A common convention is to use [NSString stringWithFormat:...] however it does not perform path appending (stringByAppendingPathComponent).

Related

Remove last portion of the NSURL: iOS

I am trying to remove just the last part of the url, Its a FTP URL.
Suppose, I have a URL like: > ftp://ftp.abc.com/public_html/somefolder/. After removing the last portion I should have it as: ftp://ftp.abc.com/public_html/.
I have tried using stringByDeletingLastPathComponenet and URLByDeletingLastPathComponent, but they dont remove the last portion correctly. They change the entire looks of the url.
for instance, after using the above said methods, here is the URL format i get ftp:/ftp.abc.com/public_html/. It removes one "/" in "ftp://", which is crashing my program.
How is it possible to removve just the last part without disturbing the rest of the URL ?
UPDATE:
NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(#"%#", urlByRemovingLastComponent);
Using above code, I get the output as :- ftp:/ftp.abc.com/public_html/
Hmm. URLByDeletingLastPathComponent works perfectly given the above input.
NSURL *url = [NSURL URLWithString:#"ftp://ftp.abc.com/public_html/somefolder/"];
NSLog(#"%#", [url URLByDeletingLastPathComponent]);
returns
ftp://ftp.abc.com/public_html/
Do you have some sample code that is yielding improper results?
Max
Now try
NSString* filePath = #"ftp://ftp.abc.com/public_html/somefolder/.";
NSArray* pathComponents = [filePath pathComponents];
NSLog(#"\n\npath=%#",pathComponents);
if ([pathComponents count] > 2) {
NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
NSLog(#"\n\nlastTwoArray=%#",lastTwoPath);
NSArray *listItems = [filePath componentsSeparatedByString:lastTwoPath];
NSLog(#"\n\nlist item 0=%#",[listItems objectAtIndex:0]);
}
output
path=(
"ftp:",
"ftp.abc.com",
"public_html",
somefolder,
"."
)
lastTwoArray =somefolder/.
list item 0 =ftp://ftp.abc.com/public_html/
An example of how to extract the last part of NSURL. In this case the location of the file. Sqlite core data
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CoreAPI.sqlite"];
NSString *localPath = [storeURL absoluteString];
NSArray* pathComponents = [localPath pathComponents];
NSLog(#"%#",[pathComponents objectAtIndex:6]);
NSString * nombre = [NSString stringWithFormat:#"%#", [pathComponents objectAtIndex:6]];
This code returns me the name of the file CoreAPI.sqlite

Crop NSURL / NSString

I got some URL's heading to certain mp3's like:
(1) localhost://blablabla/song1.mp3
(2) localhost://blablabla/songwithmorechars.mp3
and so on.
How can I crop the URL's to:
(1) song1.mp3
(2) songwithmorechars.mp3
Need to display the current song my AVAudioPlayer is playing in a UILabel.
Thanks
SOLUTION:
Here's the deal:
titleLabel.text = [[[self.audioPlayer.url absoluteString] lastPathComponent] stringByReplacingOccurrencesOfString:#".mp3" withString:#""];
Take the substring with the last / (there's a method in ObjC for that!)
NSString *sub = [url lastPathComponent];
Here's the info for that method:
NSString lastPathComponent Apple Doc
Just use [url lastPathComponent], you don't need to convert it to a string first.
use
NSString *lastString = [yourStringName lastPathComponent];
NSURL *firstURL = [NSURL URLWithString:#"localhost://blablabla/song1.mp3"];
NSString *firstString = [firstURL absoluteString];
NSLog(#"Name:%#",[firstString lastPathComponent]);
From docs:
NSURL Class Reference
NSString Class Reference

Reading Image from the Local Folder in Objective C

I need to Read a Image from the specific URL .
It works fine with WWW . but it returns a nil when the URL pointing the Local Folder .
// Works
NSString *sampleData = #"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg";
// Returns nil
NSString *sampleData = #"USER/user2/...";
Note :
I am changing the NSString to NSURL and creating the UIImage .
NSURL *url = [NSURL URLWithString: data];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
You are supplying a relative pathname for the file URL. That relative pathname is interpreted relative to the current working directory of the running application, which isn't guaranteed to be anything in particular, and so is almost certainly not what you want.
You can either supply an absolute path - one that starts with '/' - or set your app's current working directory to something explicit, like your user's Documents folder.
you probably should have a look into the NSBundle Class.
Methods like
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
or
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
is probably what you want
First of all, you can NOT read file from such path you given: "USER/user2/...", the file must in your App bundle or in your App's sandbox.
Second, check your path string if there was some texts need to be encoded in URL. Try:
NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Also, if the url is not nil, you should also check if your [NSData dataWithContentsOfURL:url]; is returning nil. If so, it means your URL is not correct so the method cannot find your file.
P.S., You are mistyping your image create code, you should call alloc before imageWithData:.
You should do something like to get the local url :
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, nameOfFile];
and finaly, load your image :
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
Try these instead
NSString *path = #"USER/user2/.../xxx.xxx";
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isFileExist = [fileManager fileExistsAtPath:path];
UIImage *image;
if (isFileExist) {
image = [[UIImage alloc] initWithContentsOfFile:path];
}
else {
// do something.<br>
}

how to delete a substring and get another part from that string

I have some string that have a type like this
NSString *string1 = #"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";
if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"
i have implement a code like this :
NSString *subString1;
int count = [string1 length];
NSLog(#"count : %d", count);
subString1 = [string1 substringFromIndex:121];
but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"
how can i do to fix it??
To get the name of your app's parent directory you should try this instead:
NSString *appUUID = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] lastPathComponent];
This will work both on a device and Simulator.
If you need to get the full path to the Documents folder inside your app sandbox:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
If you need to append a path component to a path string:
NSString *projectPath = [documentsPath stringByAppendingPathComponent: #"Project"];
Please, take a look at NSString documentation, section "Tasks", "Working with Paths". It is a must-read.
you can use stringWithRange method of NSString.
subString1 = [string1 stringWithRange:NSMakeRange(startPos,yourLengthToSelect)];
or you can use componentSeparetedByString and break string using #"/". it will return array of string. get your desired string using array index.

Troubles with NSString writeToFile

I am using the following code to open a file's contents and save it to another file.
when it runs the original file length is 793 but the saved file is 0. I have also tried just to copy the file. Nothing seems to work.
Is there some kind of permissions I'm missing on the documents directory?
NSError *error;
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* nGram = [basePath stringByAppendingPathComponent:#"contacts.gram"];
NSString *oGram = [basePath stringByAppendingPathComponent:#"/../vText.app/model/lm/TAR9230/contacts.gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:oGram encoding:NSUTF8StringEncoding error:&error];
BOOL ok = [gramString writeToFile:nGram atomically:NO encoding:NSUnicodeStringEncoding error:&error];
if(!ok) NSLog(#"Mayday!");
NSLog(#"%d",[gramString length]);
gramString = [[NSString alloc] initWithContentsOfFile:nGram encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%d",[gramString length]);
This entire block is unnecessary. All you need is:
NSString *fp=[[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:fp
encoding:NSUTF8StringEncoding
error:&error];
You certainly don't want to try to directly access a file in the app bundle using a hardcoded path because the file isn't guaranteed to be in the same exact place in every build.
In the code you do have, you want to use the same encoding constant for reading as you did for writing. You write with NSUnicodeStringEncoding but you read with NSUTF8StringEncoding. These should overlap but why take the chance if you know the exact coding used?