I have to upload images to server form iphone I am using ASIHTTPRequest for this. I have set a loop for uploading seven files. But after the executing only last file is uploaded can some one point out where I am getting it wrong.
I am using the below code for uploading :
for (int i=1; i<8; i++)
{
NSString* filename = [NSString stringWithFormat:#"Photo%d.jpg", i];
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:filename];
[request setFile:path forKey:[NSString stringWithFormat:#"file"]];
}
[request startAsynchronous];
[resultView setText:#"Uploading data..."];
My Php file code is as following :
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("vinay/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"vinay/" . $_FILES["file"]["name"]);
echo "Stored in: " . "http://serverpath" . $_FILES["file"]["name"];
}
}
?>
You're overwriting the key called file & you need to use a queue.
Do
[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];
for (int i=1; i<8; i++)
{
NSString* filename = [NSString stringWithFormat:#"Photo%d.jpg", i];
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:filename];
[request setFile:path forKey:[NSString stringWithFormat:#"file%d", i]];
[[self networkQueue] addOperation:request];
}
[[self networkQueue] go];
You're overwriting request.file, hence only the last one gets uploaded. You have to make individual requests for each file.
Or you could use [request addFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key] to send multiple files in one request.
Related
I am trying to delete the value of some Attributes in two linked Entities. Here is the code I am using:
+ (MeetPhoto *)deletePhotoForSelectedMeet:(MarksFromMeets *)specificMeet
inManagedObjectContext:(NSManagedObjectContext *)context;
{
MeetPhoto *results = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"MarksFromMeets"];
request.predicate = [NSPredicate predicateWithFormat:#"uniqueResultID = %#", specificMeet.uniqueResultID];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"uniqueResultID" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || [matches count] > 1) {
NSLog(#"There has been an error in matches in %#: \n%#.\n matches count = %lu",
NSStringFromClass([self class]),
NSStringFromSelector(_cmd),
(unsigned long)[matches count]);
} else if ([matches count] == 0){
NSLog(#"There were no matches in %#: \n%#.\n matches count = %lu",
NSStringFromClass([self class]),
NSStringFromSelector(_cmd),
(unsigned long)[matches count]);
} else {
if (debug == 1) NSLog(#"In %# and matches = %lu",NSStringFromClass([self class]),(unsigned long)[matches count]);
for (MarksFromMeets* meetEntity in matches) {
if (debug == 1) NSLog(#" MarksFromMeet = %# \n thumbnail = %# \n photo = %#",meetEntity.meetName,meetEntity.photoThumbNail,meetEntity.whichPhoto.photo);
[context deleteObject:meetEntity.photoThumbNail];
[context deleteObject:meetEntity.whichPhoto.photo];
NSError *mySavingError = nil;
[meetEntity.managedObjectContext save:&mySavingError];
if (mySavingError) NSLog(#"In %# and mySavingError is %#",NSStringFromClass([self class]), mySavingError);
}
}
return results;
}
Where whichPhoto is the title of the link between the two Core Data Entities.
Here is NSLog Statement:
2014-08-13 14:40:45.334 ITrackXC[12054:60b] thisMeetsPhoto should equal nil and equals (null)
2014-08-13 14:41:37.095 ITrackXC[12054:60b] In MeetPhotoViewController and executing imagePickerController:didFinishPickingImage:editingInfo:
2014-08-13 14:41:37.583 ITrackXC[12054:60b] In MeetPhoto and matches = 1
2014-08-13 14:41:37.589 ITrackXC[12054:60b] whichMeetPhotographed = <MarksFromMeets: 0x1700c5be0> (entity: MarksFromMeets; id: 0xd000000000300004 <x-coredata://ED56838C-9F27-451D-97CA-01AF0FC38830/MarksFromMeets/p12> ; data: {
athleteGrade = "12th Grade";
event = "5000 Meters";
eventPR = 1;
eventSB = 1;
markInEvent = "19:03";
meetDate = "2013-11-02 07:00:00 +0000";
meetID = 78103;
meetName = "OSAA 3A/2A/1A State Championships";
photoThumbNail = "<UIImage: 0x170281b80>";
placeInEvent = 2;
raceSorter = 5000;
seasonName = 2013;
sortMark = 1143;
standardOrMetric = nil;
uniqueResultID = 10032696;
whichPhoto = "0x178236d80 <x-coredata:///MeetPhoto/t9C5E481D-5911-47C9-AA8B-6015AAD1C23C2>";
whoRan = "0xd000000000080000 <x-coredata://ED56838C-9F27-451D-97CA-01AF0FC38830/AthleteInfo/p2>";
})
photo = <UIImage: 0x17009b440>
thumbnail = <UIImage: 0x170281b80>
2014-08-13 14:41:37.599 ITrackXC[12054:60b] NSManagedObjects did change.
2014-08-13 14:41:39.444 ITrackXC[12054:60b] NSManagedContext did save.
I do not get any errors. However when I look at the TableView where the data is displayed, the photos are still part of the record.
I can get rid of the thumbnail and associated photo by setting them to "nil". Is there any problem with this approach?
Setting attribute values to nil is how you're supposed to do this, so no, there's no problem with it. The deleteObject: method is only for when you want to delete a managed object. Using it in other cases might not crash, but it also won't have the effect you're aiming for.
In the case of the photo, you might need to delete an object, but it's hard to tell from your code. You seem to want to get rid of meetEntity.whichPhoto.photo. I don't know what whichPhoto is; if it's a managed object, you might want to call deleteObject on myEntity.whichPhoto to get rid of it. If nobody else is using it, that is.
I try to update my existing download-model, so I have replaced my old code:
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *data = [[NSData alloc] initWithData:responseObject];
[data writeToFile:video2Save.localFilePath atomically:YES];
video2Save.downloadComplete = YES;
[YEPersistentModelHelper saveData:_downloadVideos ToDiskWithIdentifier:persistentIdDownloadedVideos];
NSLog(#"file downloading complete : %#", video2Save.localFilePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"file downloading error : %#", [error localizedDescription]);
}];
[downloadRequest start];*/
with the following:
NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4",video2Save.videoVersionId]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
video2Save.localFilePath = [[filePath filePathURL] absoluteString];
video2Save.downloadComplete = YES;
[YEPersistentModelHelper saveData:_downloadVideos ToDiskWithIdentifier:persistentIdDownloadedVideos];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err = nil;
NSDictionary *att = [fileManager attributesOfItemAtPath:video2Save.localFilePath error:&err];
NSLog(#"NSDictionary: %#", att);
}];
[downloadTask resume];
And it seems to work fine. The complete-block is executed & the file exists at the traced target.
The problem is, that I am no longer available to play the video! I use the MPMoviePlayerController which throws this useful error:
_itemFailedToPlayToEnd: { kind = 1; new = 2; old = 0; }
The only difference seems to be the file-permissions. The first one adds a "staff"-group & everyone is allowed to read while the second only grants access for "me". But even if I change it in the finder I am not able to play it...
Does anyone has an idea!?
to save location file use path no absoluteString
video2Save.localFilePath = [[filePath filePathURL] absoluteString];
don't call absoluteString even to play.. just use the path
like this for example to call the video
NSURL *FilePathURL = [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:fileToCheck]];
[[myvideoCalss :[FilePathURL path]]
I have a custom class "Bookmark" which contains an NSString. I use a NSMutableArray to store instances of this class thus making a bookmark list which I display in a UITableView with a UITableViewCell prototype.
Would someone please give some advice/example on how to save the instances within the NSMutableArray to a file (and perhaps an example how to load them). I can't get any examples I've searched to work. I've tried converting the array to NSData and using NSKeyedArchiver without success. I've also tried converting to an NSArray but can't get it to work.
Within the custom class I've implemented encodeWithCode and initWithCoder.
I need to save before the app closes and I want to load the list when the app is started.
I'm stuck... :(
EDIT: At the request of Ageektrapped, here are the code snippets:
Inside the implementation of my Bookmark class:
- (void) encodeWithCoder: (NSCoder *) encoder
{
[encoder encodeObject:self.address forKey:#"Address"];
}
- (id) initWithCoder: (NSCoder *) decoder
{
self = [super init];
if (self != nil)
{
self.address = [decoder decodeObjectForKey: #"Address"];
}
return self;
}
In my MasterViewController
self.bookmarks is a NSMutableArray containing bookmark objects. (When the code below is called, there is at least one entry in the bookmarks array.)
NSString *docFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];
NSString *filename = [docFolder stringByAppendingPathComponent:#"data.plist"];
NSLog(#"File : %#", filename);
NSLog(#"Bookmarks : %d", self.bookmarks.count);
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: self.bookmarks ];
if ([data writeToFile: filename atomically: YES])
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
I finally figured out what my problem was.
Because I'm debugging on my iPhone device, some folders are not writable. The code I was using was asking for a location in such an area (NSDocumentationDirectory):
After finally finding =>
How can I get a writable path on the iPhone? I understood my problem and got it working.
What I needed to do was replace:
NSString *docFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];
NSString *filename = [docFolder stringByAppendingPathComponent:#"data.plist"];
with:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *libFolder = [paths objectAtIndex: 0];
NSString *filename = [libFolder stringByAppendingPathComponent: #"data.archive"];
I also changed these lines (to be consistent with the example) from:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: self.bookmarks ];
if ([data writeToFile: filename atomically: YES])
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
to:
BOOL success = [NSKeyedArchiver archiveRootObject: self.bookmarks toFile: filename];
if (success)
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
.
The code to read the file into the NSMutableArray on application startup is:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *libFolder = [paths objectAtIndex: 0];
NSString *filename = [libFolder stringByAppendingPathComponent: #"data.archive"];
self.bookmarks = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
Hei guys,
I'm trying to load a long text from a .rtf file and I want to show this text in a UITextView.
I store all the .rtf files in a folder called "rtf" into the "Supporting Files" folder.
This is my code.
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem)
{
self.textView.text = [self setTextForTextView:[self.detailItem description]];
}
}
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *path = [NSString stringWithFormat:#"rtf/%#.rtf" ,description];
NSLog(#"%#" ,path);
NSString *myText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return myText;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Text";
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
But It doesn't show me the text and I don't understand why...
Thanks!
I just solved in this way:
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:description ofType:#"txt"];
if (filePath)
{
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (myText)
{
return myText;
}
}
}
I hope this will help some people in the future! :D
I have some jpg images I am saving to the documents directory from camera shots. I want to find all the jpg images in the documents directory and load them into an array so they can be in a overflow view.
Here is my code to find and sort the jpg images in the documents directory.
NSString *extension = #"jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *jpegFiles = [NSMutableArray arrayWithCapacity: [contents count]];
NSString *filename;
for (filename in contents)
{
if ([[filename pathExtension] isEqualToString:extension])
{
[jpegFiles addObject:[UIImage imageNamed:[documentsDirectory stringByAppendingPathComponent:filename]]];
}
}
// Add the coverflow view
coverflow = [[TKCoverflowView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
coverflow.coverflowDelegate = self;
coverflow.dataSource = self;
[self.view addSubview:coverflow];
[coverflow setNumberOfCovers:6];
- (void) coverflowView:(TKCoverflowView*)coverflowView coverAtIndexWasBroughtToFront:(int)index{
NSLog(#"Front %d",index);
}
- (TKCoverflowCoverView*) coverflowView:(TKCoverflowView*)coverflowView coverAtIndex:(int)index{
TKCoverflowCoverView *cover = [coverflowView dequeueReusableCoverView];
if(cover == nil){
// Change the covers size here
cover = [[TKCoverflowCoverView alloc] initWithFrame:CGRectMake(0, 0, 280, 210)]; // 224
cover.baseline = 200;
}
cover.image = [covers objectAtIndex:index % [covers count]];
return cover;
}
I have tried everything I can think of and nothing works.
It has been suggested that I load each image by getting the path to the image from the array of pathnames, and use the method imageWithContentsOfFile to load the image.
I have looked this up and did searches for how to do this but with no luck. Could someone show me how to do this.
You should do it as below,
if ([[filename pathExtension] isEqualToString:extension])
{
[jpegFiles addObject:[UIImage imageWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:filename]]];
}