how to get NSData from video file on disk - ios

Given a url like this:
file:///private/var/mobile/Applications/C133BAE7-0CBC-4E4F-826B-509B5E1EB68E/tmp/uzhMyDkL0mSI-SCVideo-Merged.mov
How can I get the NSData representation of this to send to a server? I've tried all of these:
NSData *videoData = [NSData dataWithContentsOfURL:url];
NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];
videoData is nil every time.
EDIT:
For more context I am trying to use SCRecorder to capture video.
- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {
[session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
if (error == nil) {
//NSData *videoData = [NSData dataWithContentsOfURL:url];
//NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];
} else {
NSLog(#"Bad things happened: %#", error);
}
}];
}

The file URL looks correct to me but to be really sure, you should add in this method before trying to fetch NSData:
NSError *error = nil;
if ([url checkResourceIsReachableAndReturnError: &error] == FALSE)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
}
You can also try fetching the file via:
NSError *error = nil;
NSData *videoData = [NSData dataWithContentsOfURL:url
options: NSDataReadingUncached
error:&error];
if (videoData == nil)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
} else {
// you've likely got data, since videoData is not nil!
}

This is weird, but it works if I do this:
- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {
[session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
if (error == nil) {
[self getDataFromUrl:url];
} else {
NSLog(#"Bad things happened: %#", error);
}
}];
}
- (void)getDataFromUrl:(NSURL *)url {
NSError *error = nil;
NSData *videoData = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (videoData == nil)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
} else {
NSLog(#"GOT IT");
}
}
videoData is now valid NSData. Any explanation on why this works if separated into a different method?

Related

How to Update a file to the Content module in QuickBlox iOS

After uploading image in content module how to update image?
i'm below code to upload file code
// Upload a file to the Content module
NSData *imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"image45" ofType:#"png"]];
[QBRequest TUploadFile:imageData fileName:#"arrow.png" contentType:#"image/png" isPublic:NO successBlock:^(QBResponse *response, QBCBlob *uploadedBlob) {
// set dialog's photo
NSUInteger uploadedFileID = uploadedBlob.ID;
dialog.photo = [NSString stringWithFormat:#"%d", uploadedFileID];
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
// handle progress
} errorBlock:^(QBResponse *response) {
NSLog(#"error: %#", response.error);
}];
Find This code for update content file
NSData *file = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"plus" ofType:#"png"]];
QBCBlob *blob = [QBCBlob blob];
blob.ID = 65268; // ID of exists file
blob.name = #"Plus";
[QBRequest TUpdateFileWithData:file file:blob successBlock:^(QBResponse *response) {
// File updated
// if blob.isPublic == YES
NSString *url = [blob publicUrl];
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
// handle progress
} errorBlock:^(QBResponse *response) {
NSLog(#"error: %#", response.error);
}];

downloading video from youtube objective c

I'm trying to download video from youtube but getting error.
Error mention in code
my code
-(void)downloadVideo{
LBYouTubeExtractor *extractor = [[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"https://www.youtube.com/watch?v=%#"), videoIdToDownload ]] quality:LBYouTubeVideoQualityLarge];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError* error = nil;
NSData* data1 = [NSData dataWithContentsOfURL:videoURL options:NSDataReadingUncached error:&error]; //data1 is nill
if (error) { //Error Domain=NSCocoaErrorDomain Code=256 "The file “3gpp;+codecs="mp4v.20.3,+mp4a.40.2"&fallback_host=tc.v8.cache4.googlevideo.com&itag=36” couldn’t be opened."
NSLog(#"error=%#", error);
}else{
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), videoIdToDownload ];
[data1 writeToFile:[dirPath stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
}
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];
}
using this lib
https://github.com/larcus94/LBYouTubeView
If anyone now solution please help me.
Thanks

iOS - Why is this method so slow?

I have an iOS method that is now deprecated --NSURLConnection sendSynchronousRequest. This method worked and was fast.
I must be doing something wrong with the new method, as it is unacceptably slow.
The new method code I'm showing the whole routine is:
- (void)getData {
NSLog(#"%s", __FUNCTION__);
pathString = #"https://api.wm.com/json/jRoutes/.......";
NSURL *url = [NSURL URLWithString:pathString......];
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([response respondsToSelector:#selector(statusCode)]) {
if ([(NSHTTPURLResponse *) response statusCode] == 404) {
dispatch_async(dispatch_get_main_queue(), ^{
// alert
NSLog(#" NO DATA");
return;
});
}
}
// 4: Handle response here
[self processResponseUsingData:data];
}];
[downloadTask resume];
}
- (void)processResponseUsingData:(NSData*)data {
NSLog(#"%s", __FUNCTION__);
NSError *error = nil;
NSMutableDictionary* json = nil;
if(nil != data)
{
json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(#"Could not parse loaded json with error:%#", error);
} else {
dispatch_async(dispatch_get_main_queue(), ^{
allRoutesArray = [json valueForKey:#"Routes"];
NSLog(#"allRoutesArray count: %lu", (unsigned long)allRoutesArray.count);
[self.tableView reloadData];
});
}
}

Can we upload photos in Adobe Assets using Abode Creative SDK for iOS and Android?

Using this chunk of code only for accessing the Adobe files in my iOS project, but how can I upload my pictures in Adobe Assets cloud and save it.
[[AdobeUXAssetBrowser sharedBrowser]popupFileBrowser:^(AdobeSelectionAssetArray *itemSelections) {
NSLog(#"Selected a file");
for(id item in itemSelections) {
AdobeAsset *it = ((AdobeSelectionAsset *)item).selectedItem;
NSLog(#"File name %#", it.name);
[_statuslabel setText:fileDesc];
//If an image, let's draw it locally
NSString *fileType = ((AdobeAssetFile *)it).type;
if([fileType isEqualToString:#"image/jpeg" ] || [fileType isEqualToString:#"image/png" ]) {
NSLog(#"Going to download the image");
[((AdobeAssetFile *)it) getData:NSOperationQueuePriorityHigh
onProgress:^(double fractionCompleted) {
}
onCompletion:^(NSData *data, BOOL fromcache) {
NSLog(#"Done downloaded");
UIImage *preview = [UIImage imageWithData:data];
}
onCancellation:^(void){
}
onError:^(NSError *error) {
}
];
}
}
} onError:^(NSError *error)
{
//do nothing
NSLog(#"Error");
}];
You can find a tutorial on how to upload and download files from Creative Cloud using the CreativeSDK here:
https://creativesdk.adobe.com/docs/ios/#/articles/files/index.html
The code in particular that deals with file uploads is below:
NSData *imgData = UIImageJPEGRepresentation( yourImage, 0.8f );
NSString *dataPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"foo.jpg"];
NSURL *dataURL = [NSURL fileURLWithPath:dataPath];
NSError *err;
BOOL success = [imgData writeToFile:dataPath options:NSDataWritingAtomic error:&err];
if (success) {
AdobeAssetFolder *root = [AdobeAssetFolder getRootOrderedByField:AdobeAssetFolderOrderByName orderDirection:AdobeAssetFolderOrderDescending];
[AdobeAssetFile create:#"foo.jpg"
inFolder:root
withDataPath:dataURL
withType:kMimeTypeJPEG
withCollisionPolicy:AdobeAssetFileCollisionPolicyAppendUniqueNumber
onProgress:^(double fractionCompleted) {
NSLog(#"Percent complete %f", fractionCompleted);
}
onCompletion:^(AdobeAssetFile *file) {
NSLog(#"Uploaded");
}
onCancellation:nil
onError:^(NSError *error) {
NSLog(#"error uploading %#", error);
}];
}

authorizeRequest oAuth not called from another class?

I'm currently using Oauth2SampleTouch by Google, so people can log-in with their google accounts into my app. However whenever I call a method from The SampleRootViewController it doesn't go through the authorizeRequest method (only if I call it from another class.).
Here's the method in SampleRootViewController that I'm calling form another class.(the user is already logged in by this time)
-(NSString *)hasLikedVideo:(NSString *)videoID {
liked = #"NULL";
NSString *clientID = #"myClientID";
NSString *clientSecret = #"myClientSecret";
self.auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:clientID
clientSecret:clientSecret];
NSString *urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/videos/getRating?id=%#&key=AIzaSyB437bMtpbJh-OrkieCDRtYLe6L1Ijb3Ww", videoID];
NSLog(#"URL FOR LIKE : %# auth:(%#)", urlStr, self.auth);
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"stage 1");
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
if (error == nil) {
// the request has been authorized
NSLog(#"ERROR LOADING AUTH 1 : %#", [error description]);
} else {
NSLog(#"ERROR LOADING AUTH 2 : %#", [error description]);
}
NSLog(#"stage 2");
NSString *output = nil;
if (error) {
output = [error description];
NSLog(#"ERROR FROM LOADING LIKE INFO : %#", output);
} else {
NSLog(#"stage 3");
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
[self displayAlertWithMessage:output];
if (data) {
// API fetch succeeded
NSLog(#"stage 32");
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
// NSLog(#"%#", data);
[self displayAlertWithMessage:output];
} else {
NSLog(#"stage 34");
// fetch failed
output = [error description];
[self displayAlertWithMessage:output];
}
}
NSData* json = [output dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *allCourses = [NSJSONSerialization
JSONObjectWithData:json
options:kNilOptions
error:&error];
NSArray *monday = allCourses[#"items"];
for ( NSDictionary *theCourse in monday )
{
liked = theCourse[#"rating"];
NSLog(#"LIKE INSIDE ARRAY : %#", theCourse[#"rating"]);
}
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
}];
NSLog(#"stage 4");
return liked;
}
The method runs because I can see it log the string, however it doesn't go through the authorizeRequest, it doesn't even print out the error messages. HOWEVER if my viewController is SampleRootViewController and I call the method from itself it works.
So basically
TestViewcontroller calls a method in SampleRootViewController -> doesn't go through authorizeRequest.
SampleRootViewController calls a method in SampleRootViewController (from itself) -> goes through authorizeRequest and works.
EDIT:
I found out what I was doing "wrong"
I was calling the method like this in background
[self performSelectorInBackground:#selector(getAuthDetails) withObject:nil];
instead of
[self getAuthDetails];

Resources