Access URL of recently saved image - iphone

I am using the
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);
to save image but i want to know where it is getting saved, mean referenceURL and name of saved image..

You can get it using ALAssetsLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:myCGImage metadata:nil completionBlock:^(NSURL* assetURL, NSError* error)
{
if (error.code == 0) {
NSLog(#"URL %#", assetURL);
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
NSLog(#"Filename %#", [[asset defaultRepresentation] filename]);
}
failureBlock:^(NSError* error) {
NSLog(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}else {
NSLog(#"saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];

Related

Pocket API: how to modify data using callAPIMethod?

I would like to edit the data saved at Pocket using Pocket API with iOS SDK.
However, although the preparation method is tried, no response and error also come on the contrary.
As a premise
URLs can be added using other API (saveURL).
Permissions of the registered application are 'Add' and 'Modify'.
Is there any advice? Thanks.
NSError* error;
NSArray *actions = #[#{ #"action": #"delete", #"item_id": #"456853615" }];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: actions
options: kNilOptions
error: &error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding: NSUTF8StringEncoding];
// On ios simulator access_token is saved in NSUserDefaults, but on device in keychain.
// see https://github.com/Pocket/Pocket-ObjC-SDK/blob/master/SDK/PocketAPI.m#L718
NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey: #"PocketAPI.token"];
NSDictionary* argumentDictionary = #{#"consumer_key": #"<MY_CONSUMER_KEY>",
#"access_token": accessToken,
#"actions": jsonString};
[[PocketAPI sharedAPI] callAPIMethod: #"v3/send"
withHTTPMethod: PocketAPIHTTPMethodPOST
arguments: argumentDictionary
handler: ^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]); // response (null)
NSLog(#"error %#", [error localizedDescription]); // response (null)
}];
Drop the the API version, consumer_key & access_token. These are appended by the SDK.
NSError* error;
NSArray *actions = #[#{ #"action": #"delete", #"item_id": #"456853615" }];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: actions
options: kNilOptions
error: &error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding: NSUTF8StringEncoding];
NSDictionary* argumentDictionary = #{#"actions":jsonString};
[[PocketAPI sharedAPI] callAPIMethod:#"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:argumentDictionary
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]);
NSLog(#"error %#", [error localizedDescription]);
}];
Can use the NSDictionary to argumentDictionary.
NSDictionary *argumentDictionary = #{#"actions" : #[#{#"action" : #"delete",
#"item_id" : #"456853615"}]};
[[PocketAPI sharedAPI] callAPIMethod:#"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:argumentDictionary
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]);
NSLog(#"error %#", [error localizedDescription]);
}];

ios 7 video saving issue

Im saving the video to photolibrary.Its works for previous ios ,In ios 7
videoAtPathIsCompatibleWithSavedPhotosAlbum this line allways false
here is my code any one can help me.
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"NewmergeVideo.mov"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPathDocs];
if (fileExists) {
[[NSFileManager defaultManager] removeItemAtPath: myPathDocs error:NULL];
}
NSURL *url = [NSURL fileURLWithPath:myPathDocs];
NSLog(#"%#",url);
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL=url;
//[exporter setVideoComposition:MainCompositionInst];
exporter.outputFileType = AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^
{
dispatch_async(dispatch_get_main_queue(), ^{
[self _exportDidFinish:exporter];
});
}];
here is save code
- (void)_exportDidFinish:(AVAssetExportSession*)session
{
NSURL *outputURL = session.outputURL;
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSLog(#"%#",outputURL);
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"writeVideoToAssestsLibrary failed: %#", error);
}else{
NSLog(#"Writing3");
}
});
}];
}
[library release];
}
in previous ios nsurl
file://localhost/var/mobile/Applications/99B72CBA-A426-4F04-B7B2-2B61F0B0C513/Documents/NewmergeVideo.mov
in ios 7 nsurl
file:///var/mobile/Applications/791244EE-771B-46C9-BD57-BA0BE6CACD3C/Documents/NewmergeVideo.mov
You can Use this code to save file.(It's work correctly)
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL))
{
UISaveVideoAtPathToSavedPhotosAlbum(outputURL, self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
-(void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
if(error)
NSLog(#"Finished saving video with error: %#", error);
}

Getting NSData from an NSURL

I am trying to upload a photo from my app into a web service.
The flow I am attempting to create is as follows:
User takes photo with camera
Photo is saved to camera roll under a custom album
URL of the saved photo is given to my store
Store attempts to upload the photo to a web service.
I am trying to use NSData *data = [NSData dataWithContentsOfURL:[item assetURL]] where item is a model that contains the URL concerned. But this line is not producing a data when I log it even if it produces a URL: "assets-library://asset/asset.PNG?id=28DBC0AC-21FF-4560-A9D6-5F4BCA190BDB&ext=PNG"
The code snippets are as follows:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^(void){
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:image.imageOrientation completionBlock:^(NSURL* assetURL, NSError* error) {
BCard *card = [[BCard alloc]init];
//error handling
if (error!=nil) {
NSLog(#"[ERROR] - %#",error);
return;
}
//add the asset to the custom photo album
[library addAssetURL: assetURL
toAlbum:#"Business Cards"
withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"Custom Album Error: %#", [error description]);
}
}];
[card setAssetURL:assetURL];
[[BCardStore sharedStore]addToQueue:card];
int index = [[[BCardStore sharedStore]getQueue]count]-1;
[[BCardStore sharedStore]uploadItemAtIndex:index withProgressBlock:nil withExitBlock:nil];
}];
}];
}
and
-(void)uploadItemAtIndex:(NSUInteger)index withProgressBlock:(progressBlock)pBlock withExitBlock:(exitBlock)eBlock
{
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
NSData *data = [NSData dataWithContentsOfURL:[item assetURL]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
NSLog(#"%#",[item assetURL]);
//upload data using AFNetworking here
}
The snippet [library addAssetUrl:NSUrl toAlbum:NSString withCompletionBlock:^(NSError *error)] came from the category I found here.
Am I really getting the right URL here or am I using dataWithContentsOfURL incorrectly?
The only way is You can retrieve the UIImage from Photo-Library using ALAsset URL and convert in to NSData.
Add ALAssetLibrary
Import ALAssetLibrary header file
-(void)uploadItemAtIndex:(NSUInteger)index
withProgressBlock:(progressBlock)pBlock
withExitBlock:(exitBlock)eBlock
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep;
if([myasset defaultRepresentation] == nil) {
return;
} else {
rep = [myasset defaultRepresentation];
}
CGImageRef iref = [rep fullResolutionImage];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *myImage = [UIImage imageWithCGImage:iref];
NSData *data = //convert the myImage to NSData
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
//upload data using AFNetworking here
});//end block
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Cant get image - %#",[myerror localizedDescription]);
};
NSURL *asseturl =
[NSURL URLWithString:[self.photoPath objectAtIndex:[arrayIndex intValue] ]];
//using ARC , you have to declare ALAssetsLibrary as member variable
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL
resultBlock:resultblock
failureBlock:failureblock];
}

Retrieve facebook profile info iOS6

I have successfully prompted users to grant facebook permission, using the method below via SocialFramework, but can't seem to be able to retrieve and then display basic profile info (name, email, id, etc...) I imagine there are simple methods for this, but can't find them. Can anyone provide some help here? Thanks
-(IBAction)getInfo:(id)sender{
NSLog(#"FIRING");
ACAccountStore *_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// We will pass this dictionary in the next method. It should contain your Facebook App ID key,
// permissions and (optionally) the ACFacebookAudienceKey
NSDictionary *options = #{ACFacebookAppIdKey : #"284395038337404",
ACFacebookPermissionsKey : #[#"email"],
ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
// Request access to the Facebook account.
// The user will see an alert view when you perform this method.
[_accountStore requestAccessToAccountsWithType:facebookAccountType
options:options
completion:^(BOOL granted, NSError *error) {
if (granted)
{
NSLog(#"GRANTED");
// At this point we can assume that we have access to the Facebook account
NSArray *accounts = [_accountStore accountsWithAccountType:facebookAccountType];
// Optionally save the account
[_accountStore saveAccount:[accounts lastObject] withCompletionHandler:nil];
}
else
{
NSLog(#"Failed to grant access\n%#", error);
}
}];
}
With the code you have posted you can access only to very basic info of the account you are getting, as screen name or description which is facebook in this case...
An example:
ACAccount *account = [accounts lastObject];
NSString *username = account.username;
In order to get more complete information as real name, email, etc. you need to make a SLRequest using the /me function of the graph facebook api.
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me"];
NSString *serviceType = SLServiceTypeFacebook;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setName:#"Perform request"];
[queue addOperationWithBlock:^{
SLRequest *request = [SLRequest requestForServiceType:serviceType requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
[request setAccount:account];
NSLog(#"Token: %#", account.credential.oauthToken);
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
// Handle the response...
if (error) {
NSLog(#"Error: %#", error);
//Handle error
}
else {
NSDictionary* jsonResults = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(#"Error: Error serializating object");
//Handle error
}
else {
NSDictionary *errorDictionary = [jsonResults valueForKey:#"error"];
if (errorDictionary) {
NSNumber *errorCode = [errorDictionary valueForKey:#"code"];
//If we get a 190 code error, renew credentials
if ([errorCode isEqualToNumber:[NSNumber numberWithInt:190]]) {
NSLog(#"Renewing credenciales...");
[self.accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if (error) {
NSLog(#"Error: %#", error);
//Handle error
}
else {
if (renewResult == ACAccountCredentialRenewResultRenewed) {
//Try it again
}
else {
NSLog(#"Error renewing credenciales...");
NSError *errorRenewengCredential = [[NSError alloc] initWithDomain:#"Error reneweng facebook credentials" code:[errorCode intValue] userInfo:nil];
if (renewResult == ACAccountCredentialRenewResultFailed) {
//Handle error
}
else if (renewResult == ACAccountCredentialRenewResultRejected) {
//Handle error
}
}
}
}];
}
}
else {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(#"jsonResults: %#", jsonResults);
}];
}
}
}
}
}];
}];
This code also checks the possibility of errors, some handling if the token has expired and running the network processes in background in order to not blocking the interface.
You will find all the info at the jsonResults dictionary, and you can access as follows:
NSString *name = [jsonResults objectForKey:#"first_name"];
NSString *lastName = [jsonResults objectForKey:#"last_name"];
NSString *email = [jsonResults objectForKey:#"email"];
Check facebook documentation for more information at:
https://developers.facebook.com/docs/reference/api/user/
Hope it helps!

Saving a Video to the Photo Library - iPhone SDK

Is there any way for me to save a video in the Documents directory to the Photos Library? I have the link of the video in the documents directory, I just don't know how to save it to the Photos app.
Thanks,
Kevin
If you are saving it in a local directory first, then you can save it as..
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error){
if(error) {
NSLog(#"error while saving to camera roll %#",[error localizedDescription]);
} else {
//For removing the back up copy from the documents directory
NSError *removeError = nil;
[[NSFileManager defaultManager] removeItemAtURL:url error:&removeError];
NSLog(#"%#",[removeError localizedDescription]);
}
}];
Use the UISaveVideoAtPathToSavedPhotosAlbum function.
Try this
You can also use this code to download and save video from internet to Photos.
NSURL *videoUrl = [NSURL URLWithString:[NSString stringWithFormat:#"Your Video Url or Path"]];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
dispatch_async(dispatch_get_main_queue(), ^{
// Write it to cache directory
NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"file.mov"];
[videoData writeToFile:videoPath atomically:YES];
// After that use this path to save it to PhotoLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath] completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
{
NSLog("Error");
}
else
{
NSLog("Success");
}
}];
});
});