4

I have been faced this issue since more than a week, i am not able to get original photo/video path from assets-library url.

I can get its data by saving this file to my app SandBox, but here i want to avoid this things to again create another copy of that file.

I have investing this in DropBox, they are directly uploading from assets-library url. So, please help me to get out this issue.

Thanks in advance.

Here is my code:

-(NSString*) videoAssetURLToTempFile:(NSString*)combineURL{
self.activityIndicator.hidden = FALSE;
NSLog(@"combineURL: %@",combineURL);
NSArray *arr = [combineURL componentsSeparatedByString:@"->"];
NSString *index = [arr objectAtIndex:0];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:1]]];

//url like: "assets-library://asset/asset.MOV?id=78988A2B-203B-41B9-8EDA-F3029303DFBF&ext=MOV"

NSString * surl = [url absoluteString];
NSString * ext = [surl substringFromIndex:[surl rangeOfString:@"ext="].location + 4];

NSTimeInterval ti = [[NSDate date]timeIntervalSinceReferenceDate];
NSString *fname = [NSString stringWithFormat: @"%f.%@",ti,ext];

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"SAVED_PHOTOS"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

NSString *tmpfile = [stringPath stringByAppendingPathComponent:fname];

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
    ALAssetRepresentation * rep = [myasset defaultRepresentation];
    NSLog(@"video url: %@",rep.url);
    NSUInteger size = [rep size];

    NSLog(@"file size: %@",[NSString stringWithFormat:@"%llu",(unsigned long long)rep.size]);
    if (!appDelegate.arrFileSize) {
        appDelegate.arrFileSize = [[NSMutableArray alloc] init];
    }
    [appDelegate.arrFileSize replaceObjectAtIndex:[index integerValue] withObject:[NSString stringWithFormat:@"%llu",(unsigned long long)rep.size]];
    [appDelegate.accessToken setObject:appDelegate.arrFileSize forKey:@"FileSize"];
    [appDelegate.accessToken synchronize];
    NSLog(@"video fileSize: %@",[self convertbyteToKB_MB:(unsigned long long)rep.size]);
    unsigned long long freeSpaceSize = [self getFreeDiskspace];
    NSLog(@"freeSpaceSize: %llu",freeSpaceSize);

    if (freeSpaceSize<rep.size && rep.size<1073741824) {
        NSString *alertMsg;
        if (IS_IPHONE) {
            alertMsg = [NSString stringWithFormat:@"App requires %@ free storage space to upload this video. To proceed with this upload, please go to your iPhone's Settings and clear some space.",[self convertbyteToKB_MB:(unsigned long long)rep.size]];
        }
        else{
            alertMsg = [NSString stringWithFormat:@"App requires %@ free storage space to upload this video. To proceed with this upload, please go to your iPad's Settings and clear some space.",[self convertbyteToKB_MB:(unsigned long long)rep.size]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:alertMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = TRUE;
            });
        });

    }
    else{
        if (rep.size>=1073741824) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = TRUE;
            });
        }
        else{
            convertingTotal++;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = FALSE;
            });
            const int bufferSize = 8*1024*1024;
            FILE* f = fopen([tmpfile cStringUsingEncoding:1], "wb+");
            if (f == NULL) {
                return;
            }

            Byte * buffer = (Byte*)malloc(bufferSize);
            unsigned long long read = 0, offset = 0, written = 0;
            NSError* err;
            if (size != 0) {

                do {
                    read = (unsigned long long)[rep getBytes:buffer
                                                  fromOffset:offset
                                                      length:bufferSize
                                                       error:&err];
                    written = (unsigned long long)fwrite(buffer, sizeof(char), read, f);
                    offset += read;
                } while (read != 0);
                blockedNo++;
            }
            fclose(f);
            NSLog(@"file saved to temp");
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"total: %d blockedNo: %d",convertingTotal,blockedNo);
                self.waitToUploadLbl.hidden = TRUE;
           });
        }
    }

};

ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
{
    //NSLog(@"Can not get asset - %@",[myerror localizedDescription]);

};

if(url)
{
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:url
                   resultBlock:resultblock
                  failureBlock:failureblock];
}
self.activityIndicator.hidden = TRUE;
@try {
    [appDelegate.uploadArray1 replaceObjectAtIndex:[index integerValue] withObject:tmpfile];
    [appDelegate.accessToken setObject:appDelegate.uploadArray1 forKey:@"UploadArray"];
    [appDelegate.accessToken synchronize];
    NSLog(@"temporary path: %@",tmpfile);
    [self performSelector:@selector(uploadphotoToServer:) withObject:index afterDelay:1];
}
@catch (NSException *exception) {
    NSLog(@"Error: %@",exception);
}
@finally {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (convertingTotal==blockedNo) {
            self.waitToUploadLbl.hidden = TRUE;
        }

    });
}
return tmpfile;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Pratik Patel
  • 1,393
  • 12
  • 18
  • This is how i managed to first save video to desired folder and then upload to server from that path. I want to remove this saving process and direct want to upload from "assets-library://asset/asset.MOV?id=22193DF9-2B64-4E43-AB01-A16E356FD2E6&ext=MOV" this url. – Pratik Patel Jun 25 '14 at 10:57
  • yes, you can try to upload one video file around 500MB, it will not increase your app usage in settings. It remains same, and when i tried same video file in my app it shows 500MB+appSize, total 553MB in usage. – Pratik Patel Jun 25 '14 at 11:00

1 Answers1

2

i hope this will help you

NSString *str_url=[arrURL objectAtIndex:indexPath.row];//put your index

                    ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];

                    NSURL* aURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",str_url]];

                    [assetLibrary assetForURL:aURL resultBlock:^(ALAsset *asset) {

                        ALAssetRepresentation *rep = [asset defaultRepresentation];
                        Byte *buffer = (Byte*)malloc(rep.size);
                        NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
                        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

                        cell.imageCell.image=[UIImage imageWithData:data];


                    } failureBlock:^(NSError *error)
                     {
                         NSLog(@"Error: %@",[error localizedDescription]);
                     }];
  • Thanks for your reply. But i want original image/video file for upload. If i take NSData for video upload which is around 500MB app returns memory warning and then crash. Also UI is unresponsive. I want a path from where i can directly upload a file without saving that file into memory or NSDirectory. – Pratik Patel May 02 '16 at 04:17