ASIHTTPRequestErrorDomain Code=8. Cannot move file from temp directory to docs - objective-c

I download files with ASIHTTPReqeust. Everything downloads fine but it can't move file from temp directory to documents. When i implement
-(void) request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
request fails with an error. But file is downloaded.
If i remove this implementation, everything is fine, and files are moving to docs.
Here is Error text:
Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'" UserInfo=0x5949520 {NSUnderlyingError=0x59992a0 "The operation couldn’t be completed. (Cocoa error 4.)", NSLocalizedDescription=Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'}
Who had similar problem?

Something that often catches people out is that you have to create the directory that you're downloading into yourself (ASIHTTPRequest won't create it automatically).
However given you say it's related to the implementing didReceiveData it's not that.
If you look at ASIHTTPRequest.m, you'll see it sets 'dataWillBeHandledExternally' if you implement 'didReceiveData' in the delegate - this will be preventing the data being written to disk. You can either write the data yourself, or you could change the ASIHTTPRequest.m code to add a flag to force it to handle the data internally too.

I encountered same error, but the reason was different. I will post my problem - just in case anyone else has similar situation.
I was trying to delete old images, before saving new ones.
NSString *mImgName = [managedObj valueForKey:#"aImgName"];
NSString * mFilePath = [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:mImgName];
if ([mFileManager fileExistsAtPath:mFilePath])
{
[mFileManager removeItemAtPath:mFilePath error:nil];
}
Problem was - in case mImgName is nil, mFileManager will delete whole directory.
By adding extra checking for nil or too short mImgName value, it solved problem.
Hopefully it will help someone!

Related

How to export package files in document based application on OSX?

in my app, I want to load certain image user picks, make some modification, after that, save a copy in my own file format. Since I want to keep track of user modification, I decided to export my file as a package(bundle).
So, in my document class, there's a NSImage object that holds the image file. In the fileWrapperOfType:error: method, I've setup a NSFileWrapper object, and put the object in it. Here's the code:
NSDictionary *fileWrappers = [self.documentFileWrapper fileWrappers];
if (image != nil) {
NSBitmapImageRep *imageRep = [image bitmapImageRepresentation];
NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
NSFileWrapper *imageFileWrapper = [[NSFileWrapper alloc]
initRegularFileWithContents:imageData];
[imageFileWrapper setPreferredFilename:#"image"];
[[self documentFileWrapper] addFileWrapper:imageFileWrapper];
}
return self.documentFileWrapper;
In my project plist file, I have two document types, first is the type of public.image since I need to load images in my app:
The other one is my own document type. To make the file a package, I've checked the bundle checkbox in xcode:
If I simply run this now, the code compains that finding extension from type identifier is deprecated, so, I managed to add an entry in Exported UTIs:
At this moment, everything seems working, except that the outputed folder with mdc extension, is indeed a folder instead of a package, what am I missing here? Thanks in advance!
Finally I solved the problem, the key here is to change Conforms To field to com.apple.package.
In order for a package on OS X to be a pkg, it must have a .pkg extension. I hope it is as simple as having the wrong extension.
Note: Until recently, .pkg files were merely directories. Now, we often see package.pkg packages that are obscured cannot be browsed causually without some tricks like using Pacifist, pkgutil or xar:
pkgutil --extract file.pkg folder/
or
xar -xf file.pkg

Documents not Uploading to iCloud when using For Loops - iOS

I am attempting to upload a local folder full of documents to a remote iCloud folder. I wrote this method to loop through the array of files in the local folder, check if they already exist, and if they don't exist upload them to iCloud. Note- this code is being executed on the background thread not the main thread.
//Get the array of files in the local documents directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *localDocuments = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
//Compare the arrays then upload documents not already existent in iCloud
for (int item = 0; item < [localDocuments count]; item++) {
//If the file does not exist in iCloud, upload it
if (![[iCloud previousQueryResults] containsObject:[localDocuments objectAtIndex:item]]) {
NSLog(#"Uploading %# to iCloud...", [localDocuments objectAtIndex:item]);
//Move the file to iCloud
NSURL *destinationURL = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#",[localDocuments objectAtIndex:item]]];
NSError *error;
NSURL *directoryURL = [[NSURL alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:[localDocuments objectAtIndex:item]]];
BOOL success = [[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:directoryURL destinationURL:destinationURL error:&error];
if (success == NO) {
//Determine Error
NSLog(#"%#",error);
}
} else {
...
} }
When I run this code the For Loop works fine - I use NSLog statements to find out which file it is uploading - and every file stored locally that isn't already in iCloud is supposed to start uploading. After the For Loop is finished I check which documents are now in iCloud using developer.icloud.com. Only one file (an sqlite file that my app keeps making but never uses) out of the many stored locally uploads to iCloud. Why would only one file upload when using for loops?
When I use the same code to upload individual files (without a For Loop) they upload to iCloud perfectly. Why would a For Loop hinder the uploading of files? Does this have to do with the For Loop continuing to the next line of code without waiting for the last process / line to finish executing? What's going on here?
EDIT: Usually when I upload large files to iCloud (without using a For Loop) I can see on the iCloud dev site that the file is Pending Upload almost instantly. I'm testing everything over WiFi and I've been waiting a while but nothing appears (except for the sqlite file).
EDIT: I also check for iCloud availability in a different method which then allows calls to this method if iCloud is available. I've also made sure to read over the documentation and watched the WWDC videos on Apple's website, however they are complex and don't provide much explanation for what I'm trying to do.
EDIT: After revising the code above (adding the error functionality), I now get this error message in the log:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x1f5dd070 {NSUnderlyingError=0x208ad9b0 "The operation couldn’t be completed. (LibrarianErrorDomain error 2 - No source URL specified.)"}
This makes things even more confusing because one of the files uploads successfully, whereas the others do not.
OK, that last edit is useful. The error complains that the source URL (directoryURL in your code) is missing-- probably because it's nil. Why would it be nil? Because you're creating it wrong. You're using -[NSURL initWithString:], and the docs say that:
This string must conform to URL format as described in RFC 2396. This method parses URLString according to RFCs 1738 and 1808.
You're passing in a file path, not a URL. If you pass NSURL something it doesn't recognize as a valid URL, it normally returns nil. It looks like NSURL will frequently produce a file URL anyway, but failure is the expected behavior here. From what I can tell it seems to work if the filename contains no spaces, but that's not documented and not something you could rely on.
What you should do is change the line where you initialize directoryURL to use something that accepts a file path. Something like:
NSURL *directoryURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[localDocuments objectAtIndex:item]]];
Also, make sure to verify that directoryURL is not nil, just in case.

Core Data adding entities at runtime

I am rewriting the question to help clarify and get rid of a lot of code I wrote that really doesn't help.
I am using a .xcdatamodel for my initial schema, but I need to add entities to my schema at runtime and therefore I need to add a new NSManagedObjectModel and copy over the existing entities and then add the new entities.
If I create a new NSPersistantStore first and then ask my NSMigrationManager to migrate, I get an error about how it can't move the source model to destination path because file already exists.
If I simply ask my NSMigrationManager to migrate, then it just crashes without any error codes or anything in the debugger.
NSMappingModel *mappingModel = [NSMappingModel inferredMappingModelForSourceModel:originalModel destinationModel:newModel error:&error];
NSMigrationManager *manager = [[NSMigrationManager alloc] initWithSourceModel:originalModel destinationModel:newModel];
if (![manager migrateStoreFromURL:[originalStore URL]
type:NSSQLiteStoreType
options:[self autoMigrationOptions]
withMappingModel:mappingModel
toDestinationURL:[NSPersistentStore MR_urlForStoreName:[self nextStoreName]]
destinationType:NSSQLiteStoreType
destinationOptions:[self autoMigrationOptions]
error:&error])
{
return NO;
}
The URL's are all good, the mapping model looks good when I log it to the console, the manager exists, etc. In this case I did not create the NSPersistantStore yet, but according to the NSMigrationManager class reference if a store does not exist at the destination URL then one is automatically created.
Anyone have a clue?

Accessing the media:group of XML returned by GData's Obj-C library for Accessing YouTube Playlists

I have seen a couple similar questions about this, however none of them work correctly.
(I am guessing Google updated the GData Objective-C library since those questions)
The 2 similar questions are:
Load YouTube GData feed for a single video by id
gdata youtube query problem
The way #grobbins explains to do it in the first link is as follows:
for (GDataEntryYouTubeVideo *videoEntry in [feed entries]) {
GDataYouTubeMediaGroup *mediaGroup = [videoEntry mediaGroup];
NSString *videoID = [mediaGroup videoID];
NSArray *mediaContents = [mediaGroup mediaContents];
GDataMediaContent *flashContent =
[GDataUtilities firstObjectFromArray:mediaContents
withValue:#"application/x-shockwave-flash"
forKeyPath:#"type"];
NSLog(#"video ID = %#, flash content URL = %#",
videoID, [flashContent URLString]);
}
The problem is that calling 'mediaGroup' throws 'unrecognized selector sent to instance...'
I have tried this with setting up videoEntry as both GDataEntryBase and GDataEntryYouTubeVideo (which is a subclass of GDataEntryBase) and no matter what the debugger shows the variable videoEntry is always of the type GDataEntryBase (even when specifying GDataEntryYouTubeVideo as above)
I could grab the XML out and parse it myself, but then whats the point of using the library?
(Plus on Googles site it says you should never need to parse the XML directly)
What am I doing wrong?
How do I get the mediaGroup section of a returned Playlist?
FetchFeedWithURL: loads my method when finished, and my method has a header of:
- (void)loadedPlaylist:(GDataServiceTicket*)ticket finishedWithFeed:(GDataFeedBase*)feed error:(NSError*)error;
Found the problem!
The problem was that I forgot to add: -ObjC -all_load, to my Other Linker Flags.
Once I added those, the feed entries are coming back as type GDataEntryYouTubePlaylist.
Hope this helps someone else.

NSBundle bundleWithPath fails

I am trying to load a bundle using bundleWithPath but it always fails (returns nil)
I was wondering what can be teh reasons why it fails and what are the way to het more information about the error.
Thanks in advance for your help!
Regards,
The failure may have many reasons: the file doesn't exist, the file exist but not in the path you are looking for. It has some different extention. Or the file at your path is not in correct bundle format. That's all I can tell you without code.
From the documentation:
+bundleWithPath:
Returns an NSBundle object that corresponds to the specified directory.
+ (NSBundle *)bundleWithPath:(NSString *)fullPath
Return Value: The NSBundle object that corresponds to fullPath, or nil if fullPath does not identify an accessible bundle directory.