Uploading Image to Dropbox - objective-c

I'm trying to upload an image to dropbox. I'm using the latest version of the SDK (Sept. 17) and have successfully authenticated my app.
Here's the code that does it:
for ( NSUInteger i = 0; i < [photos count]; i ++ ) {
NSString *filename = [NSString stringWithFormat:#"%d.png", i+1];
NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[UIImagePNGRepresentation([photos objectAtIndex:i]) writeToFile:file atomically:YES];
NSString *destDir = #"/";
[self.dropboxClient uploadFile:filename toPath:destDir withParentRev:nil fromPath:file];
}
Note:
self.dropboxClient is an instanced DBRestClient object.
photos is an NSMutableArray of UIImages (I already checked to make sure that the objects are images using the NSStringFromClass() method on each object in the list);
Most importantly, I think there may be an issue with my DBRestClient object (self.dropboxClient), since none of the delegate methods are entered even though I've set the delegate.
Any and all help would be greatly appreciated!

This was a threading issue. DBRestClient methods, like createFolder and uploadFile:::: must be executed on the main thread.

Related

How to get all images in the project folder that start with a specific string

I am quite new in iOS development and Objective-C and I would appreciate some help.
I created a Group folder in Xcode where I placed all my images. All my images are inside the project folder.
I want to iterate through the Xcode folder routineIcons and get all Images that have b- in their name and put their name and extension into an array.
Could anyone point me in the right direction on how to do this? bah.. is it possible??
You can use this snipped:
NSMutableArray *result = [NSMutableArray array];
[[[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil] enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
NSString *path = [obj lastPathComponent];
if ([path hasPrefix:#"b-"]) {
[result addObject:path];
}
}];
At runtime, the routineIcons folder won't exist. All of those images, along with all other resources, will end up in the app's resource bundle.
What you can do is get the path to the resource bundle then use NSFileManager to get all of the files in the folder. You can then ignore any that don't start with "b-".

Why my program can run in Xcode, but cannot running as a separate app?

My program loads some data from a file and then draws them.
The file-reading part is like this:
- (void)load_file
{
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:#"map_data"];
NSData *myData=[inFile readDataToEndOfFile];
NSString *myText=[[NSString alloc]initWithData:myData encoding:NSASCIIStringEncoding];
NSArray *values = [myText componentsSeparatedByString:#"\n"];
for (NSString *string in values) {
NSArray *lines=[string componentsSeparatedByString:#" "];
if ([lines count] != 2) break;
NSPoint point= NSMakePoint([lines[0] floatValue], [lines[1] floatValue]);
[points addObject:[NSValue valueWithPoint:point]];
}
[self setNeedsDisplay:YES];
}
When debugging, I put the data file in the directory of [NSBundle mainBundle], and the program works fine.
However, when I use achieve to take the app out, it never runs. I put the data file in the same path with the app, but it seems fail to load it.
Update
I tried to use c++, but still fails.
- (void)load_file
{
ifstream inf("map_data");
double x, y;
while (inf >> x >> y) [points addObject:[NSValue valueWithPoint:NSMakePoint(x, y)]];
inf.close();
}
I tried to change the build scheme to release and run, which is fine. But whenever I go directly into the finder of app and double click it, it does not work and seems nothing is loaded.
add the file to the project as a Resource (this will cause it to be copied into the app wrapper in the right spot)
use `[[NSBundle mainBundle] pathForResource:#"map_data" ofType:nil];
That should give you the path to the file. The file should not be manually copied, it should not be next to the app wrapper, nor should you [conjecture] ever try changing or replacing the file once it is in your app wrapper.
The reason why it seems to work sometimes is mere coincidence. You are passing a partial path to NSFileHandle and it happens that the current working directory of your app sometimes points to the right spot such that the data file is available.
I'm not sure how relative paths are handled by NSFileHandle, but usually you set up paths using the NSBundle class.
NSString *path = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"ext"];
You can also simply initialize an NSString from the contents of a file, you don't need to first read it into an NSData using NSFileHandle.
NSString *text = [[NSString alloc] initWithContentsOfFile:path
encoding:NSASCIIStringEncoding error:nil];
(Use the error parameter, if you want proper error handling)

EXC_BAD_ACCESS on NSString sizeWithFont

I am not sure what is going on anymore. I have tried so many things to for me to figure out whats going on on this specific line of code that is causing a EXC_BAD_ACCESS.
I tried enabled NSZombies but it didn't help me any. Here is the code:
- (int)linesFromText:(NSString *)string withFont:(UIFont *)font andSize:(CGSize)size {
NSArray *splitString = [string componentsSeparatedByString:#" "];
NSMutableArray *allLines = [NSMutableArray array];
NSMutableString *line = [NSMutableString string];
NSString *word;
NSString *fakeLine;
for (int i = 0; i < splitString.count; i++) {
word = [splitString objectAtIndex:i];
fakeLine = [NSString stringWithFormat:#"%#%# ",line, word];
//NSLog(#"line %#, font %#",fakeLine,font);
////THIS IS THE LINE CAUSING THE EXC_BAD_ACCESS
CGSize lineSize = [fakeLine sizeWithFont:font];
if (lineSize.width <= size.width) {
[line appendFormat:#"%# ", word];
} else {
[allLines addObject:[line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
line = [NSMutableString string];
[line appendFormat:#"%# ", word];
}
}
[allLines addObject:[line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
return allLines.count;
}
This is driving me crazy cause it only happens on the new iphone 5 when you scroll through the days to fast in the app I built. Here is a link to the application in the store:
http://itunes.apple.com/us/app/id543324451?mt=8
if you have an iphone 5 you can see what I mean. iphone 4 doesn't do this.
This code is being called in a UITableViewCell's layoutSubviews and is there to help size the frame of a Custom Attributed label that uses TTTAttributedLabel (https://github.com/mattt/TTTAttributedLabel).
I also tried to enable "Gaurd malloc to try give me more details but my XCode gives me this error:
dyld: could not load inserted library '/usr/lib/libgmalloc.dylib' because image not found
which if I look in /usr/lib that file is a sym link to a file that does exist in the same directory:
libgmalloc.dylib -> libgmalloc.B.dylib
I am running out of ideas here and thought it might be the UIFont getting released to soon and then it not being available so I put references in the UITableViewCell to hold the UIFont until the end of that Cell's life.
I have also searched around the internet and haven't found that much on this specifics.
Also here is an image of my stack trace from debugger:
http://i.stack.imgur.com/gWC5L.png
Any ideas?
Did I provide enough info?
Thanks
I think your question is answered here:
UIStringDrawing methods don't seem to be thread safe in iOS 6
The short version: sizeWithFont, and most other UIKit methods, are not thread safe when you're using it on the screen (rather than using it to pre-render).
The good news: look at Adam Swinden's answer in that thread; he explains how to get the same result in iOS6 with CoreText instead of UIKit.

Calling -[NSFileManager setUbiquitous:itemAtURL:destinationURL:error:] never returns

I have a straightforward NSDocument-based Mac OS X app in which I am trying to implement iCloud Document storage. I'm building with the 10.7 SDK.
I have provisioned my app for iCloud document storage and have included the necessary entitlements (AFAICT). The app builds, runs, and creates the local ubiquity container Documents directory correctly (this took a while, but that all seems to be working). I am using the NSFileCoordinator API as Apple recommended. I'm fairly certain I am using the correct UbiquityIdentifier as recommended by Apple (it's redacted below tho).
I have followed Apple's iCloud Document storage demo instructions in this WWDC 2011 video closely:
Session 107 AutoSave and Versions in Lion
My code looks almost identical to the code from that demo.
However, when I call my action to move the current document to the cloud, I experience liveness problems when calling the -[NSFileManager setUbiquitous:itemAtURL:destinationURL:error:] method. It never returns.
Here is the relevant code from my NSDocument subclass. It is almost identical to Apple's WWDC demo code. Since this is an action, this is called on the main thread (as Apple's demo code showed). The deadlock occurs toward the end when the -setUbiquitous:itemAtURL:destinationURL:error: method is called. I have tried moving to a background thread, but it still never returns.
It appears that a semaphore is blocking while waiting for a signal that never arrives.
When running this code in the debugger, my source and destination URLs look correct, so I'm fairly certain they are correctly calculated and I have confirmed the directories exist on disk.
Am I doing anything obviously wrong which would lead to -setUbiquitous never returning?
- (IBAction)moveToOrFromCloud:(id)sender {
NSURL *fileURL = [self fileURL];
if (!fileURL) return;
NSString *bundleID = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleIdentifier"];
NSString *appID = [NSString stringWithFormat:#"XXXXXXX.%#.macosx", bundleID];
BOOL makeUbiquitous = 1 == [sender tag];
NSURL *destURL = nil;
NSFileManager *mgr = [NSFileManager defaultManager];
if (makeUbiquitous) {
// get path to local ubiquity container Documents dir
NSURL *dirURL = [[mgr URLForUbiquityContainerIdentifier:appID] URLByAppendingPathComponent:#"Documents"];
if (!dirURL) {
NSLog(#"cannot find URLForUbiquityContainerIdentifier %#", appID);
return;
}
// create it if necessary
[mgr createDirectoryAtURL:dirURL withIntermediateDirectories:NO attributes:nil error:nil];
// ensure it exists
BOOL exists, isDir;
exists = [mgr fileExistsAtPath:[dirURL relativePath] isDirectory:&isDir];
if (!(exists && isDir)) {
NSLog(#"can't create local icloud dir");
return;
}
// append this doc's filename
destURL = [dirURL URLByAppendingPathComponent:[fileURL lastPathComponent]];
} else {
// get path to local Documents folder
NSArray *dirs = [mgr URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
if (![dirs count]) return;
// append this doc's filename
destURL = [[dirs objectAtIndex:0] URLByAppendingPathComponent:[fileURL lastPathComponent]];
}
NSFileCoordinator *fc = [[[NSFileCoordinator alloc] initWithFilePresenter:self] autorelease];
[fc coordinateWritingItemAtURL:fileURL options:NSFileCoordinatorWritingForMoving writingItemAtURL:destURL options:NSFileCoordinatorWritingForReplacing error:nil byAccessor:^(NSURL *fileURL, NSURL *destURL) {
NSError *err = nil;
if ([mgr setUbiquitous:makeUbiquitous itemAtURL:fileURL destinationURL:destURL error:&err]) {
[self setFileURL:destURL];
[self setFileModificationDate:nil];
[fc itemAtURL:fileURL didMoveToURL:destURL];
} else {
NSWindow *win = ... // get my window
[self presentError:err modalForWindow:win delegate:nil didPresentSelector:nil contextInfo:NULL];
}
}];
}
I don't know if these are the source of your problems, but here are some things I'm seeing:
-[NSFileManager URLForUbiquityContainerIdentifier:] may take a while, so you shouldn't invoke it on the main thread. see the "Locating the Ubiquity Container" section of this blog post
Doing this on the global queue means you should probably use an allocated NSFileManager and not the +defaultManager.
The block passed to the byAccessor portion of the coordinated write is not guaranteed to be called on any particular thread, so you shouldn't be manipulating NSWindows or presenting modal dialogs or anything from within that block (unless you've dispatched it back to the main queue).
I think pretty much all of the iCloud methods on NSFileManager will block until things complete. It's possible that what you're seeing is the method blocking and never returning because things aren't configured properly. I'd double and triple check your settings, maybe try to simplify the reproduction case. If it still isn't working, try filing a bug or contacting DTS.
Just shared this on Twitter with you, but I believe when using NSDocument you don't need to do any of the NSFileCoordinator stuff - just make the document ubiquitous and save.
Hmm,
did you try not using a ubiquity container identifier in code (sorry - ripped out of a project so I've pseudo-coded some of this):
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *iCloudDocumentsURL = [[fm URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:#"Documents"];
NSURL *iCloudFileURL = [iCloudDocumentsURL URLByAppendingPathComponent:[doc.fileURL lastPathComponent]];
ok = [fm setUbiquitous:YES itemAtURL:doc.fileURL destinationURL:iCloudRecipeURL error:&err];
NSLog(#"doc moved to iCloud, result: %d (%#)",ok,doc.fileURL.fileURL);
And then in your entitlements file:
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>[devID].com.yourcompany.appname</string>
</array>
Other than that, your code looks almost identical to mine (which works - except I'm not using NSDocument but rolling it all myself).
If this is the first place in your code that you are accessing iCloud look in Console.app for a message like this:
taskgated: killed yourAppID [pid 13532] because its use of the com.apple.developer.ubiquity-container-identifiers entitlement is not allowed
Anytime you see this message delete your apps container ~/Library/Containers/<yourAppID>
There may also be other useful messages in Console.app that will help you solve this issue.
I have found that deleting the app container is the new Clean Project when working with iCloud.
Ok, So I was finally able to solve the problem using Dunk's advice. I'm pretty sure the issue I was having is as follows:
Sometime after the WWDC video I was using as a guide was made, Apple completed the ubiquity APIs and removed the need to use an NSFileCoordinator object while saving from within an NSDocument subclass.
So the key was to remove both the creation of the NSFileCoordinator and the call to -[NSFileCoordinator coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor:]
I also moved this work onto a background thread, although I'm fairly certain that was not absolutely required to fix the issue (although it was certainly a good idea).
I shall now submit my completed code to Google's web crawlers in hopes of assisting future intrepid Xcoders.
Here's my complete solution which works:
- (IBAction)moveToOrFromCloud:(id)sender {
NSURL *fileURL = [self fileURL];
if (!fileURL) {
NSBeep();
return;
}
BOOL makeUbiquitous = 1 == [sender tag];
if (makeUbiquitous) {
[self displayMoveToCloudDialog];
} else {
[self displayMoveFromCloudDialog];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doMoveToOrFromCloud:makeUbiquitous];
});
}
- (void)doMoveToOrFromCloud:(BOOL)makeUbiquitous {
NSURL *fileURL = [self fileURL];
if (!fileURL) return;
NSURL *destURL = nil;
NSFileManager *mgr = [[[NSFileManager alloc] init] autorelease];
if (makeUbiquitous) {
NSURL *dirURL = [[MyDocumentController instance] ubiquitousDocumentsDirURL];
if (!dirURL) return;
destURL = [dirURL URLByAppendingPathComponent:[fileURL lastPathComponent]];
} else {
// move to local Documentss folder
NSArray *dirs = [mgr URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
if (![dirs count]) return;
destURL = [[dirs firstObject] URLByAppendingPathComponent:[fileURL lastPathComponent]];
}
NSError *err = nil;
void (^completion)(void) = nil;
if ([mgr setUbiquitous:makeUbiquitous itemAtURL:fileURL destinationURL:destURL error:&err]) {
[self setFileURL:destURL];
[self setFileModificationDate:nil];
completion = ^{
[self hideMoveToFromCloudDialog];
};
} else {
completion = ^{
[self hideMoveToFromCloudDialog];
NSWindow *win = [[self canvasWindowController] window];
[self presentError:err modalForWindow:win delegate:nil didPresentSelector:nil contextInfo:NULL];
};
}
dispatch_async(dispatch_get_main_queue(), completion);
}

iOS/iPhone SDK: initWithCoder and encodeWithCoder not being called

I'm trying to save an NSMutableArray called queueArray so it can be loaded again after the app has been quit. I used a few tutorials to get me going and this is the code I have come up with. The problem seems to be that "initWithCoder" and "encodeWithCoder" are not being called, shown by no NSLog calls and no stopping at breakpoints. I have added the NSCoding protocol to the .h file and I know that queueArray is not nil and it contains MPMediaItems. Here is some of the code I use to try to save and load the array:
-(IBAction)saveQueuePressed {
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:#"queueArray.archive"];
//should cause encodeWithCoder to be called
[NSKeyedArchiver archiveRootObject:queueArray toFile:filePath];
}
-(IBAction)loadQueuePressed {
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:#"queueArray.archive"];
//should cause initWithCoder to be called
queueArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
-(void)encodeWithCoder:(NSCoder *)coder {
NSLog(#"encodeWithCoder");
[coder encodeObject:queueArray forKey:#"savedQueueArray"];
}
-(id)initWithCoder:(NSCoder *)decoder {
NSLog(#"initWithCoder");
queueArray = [decoder decodeObjectForKey:#"savedQueueArray"];
return self;
}
Any help will be greatly appreciated!
The encodeWithCoder: and initWithCoder methods are called when you archive/unarchive an object that responds to them. From what I understand, you have those methods in your class, but the object you are actually archiving (queueArray) is not an instance of that class, it's an NSMutableArray.
If you do want to save your entire object, you can change your saveQueue method to this
-(IBAction)saveQueuePressed {
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:#"queueArray.archive"];
// saving the array shouldn't, but saving the self object
//should cause encodeWithCoder to be called:
[NSKeyedArchiver archiveRootObject:self toFile:filePath];
}
But if you just want to save the array, I guess you can just use saveQueuePressed and loadQueuePressed, I don't think you need the encode/init WithCoder: methods
Update:
Maybe your path is not right.
Try
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[rootPath stringByAppendingPathComponent:#"queueArray.archive"] stringByExpandingTildeInPath]];
Filipe is right! Your comment said you still didn't use his method.
I had this issue too. Switching from the dictionary's atomic write method to the keyedArchiver fixed it, luckily I only had to change one thing, the line that said writeToFile: is now the archive function.
Now my program's working. For some reason, even when responding to NSCoding, the custom object is not being encoded and breaks my dictionary. Is this a bug with iOS? I've read a fair number of Apple Manuals, but I've also seen a fair number of typos and missing info (For example, try MKMapRect functions without the videos to explain them), or Core Animations referencing the Run Loop before you learn threading, I could go on, half finished sentences in Quartz... so yeah, I've read the manuals and this perplexes me, we have to get a more open iOS SDK at some point, hopefully