I am using a standard UIDocumentInteractionController in my app, and provide it with a local image URL.
However, once Viber is selected, it first sends a plain text message with the file URL and then the image. I only want to send the image ofcourse.
I see that it's working allright from the native Gallery, so it's obviously my fault.
here's the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/tempName.jpg"];
MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:imgPicker.view];
HUD.mode = MBProgressHUDModeAnnularDeterminate;
[imgPicker.view addSubview:HUD];
[HUD show:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
_documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL URLWithString:path]];
[_documentInteractionController setUTI:(NSString *)kUTTypeJPEG];
_documentInteractionController.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
[HUD removeFromSuperview];
[_documentInteractionController presentOptionsMenuFromRect:CGRectZero inView:imgPicker.view animated:YES]; });
});
Related
My code is here:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,strFileName];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
[self openDocumentIn:filePath];
});
}
});
- (void)openDocumentIn:(NSString*)path {
[self dismissViewControllerAnimated:YES completion:nil];
controller = [[UIDocumentInteractionController alloc] init];
controller.URL = [NSURL fileURLWithPath:path];
controller.delegate = self;
controller.UTI = #"com.adobe.pdf";
[controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
}
The above code is working properly for iPhone, but it does not working in iPad.
I am trying to share an image on the Instagram application through my application.
Please check my code below and please let me know where I have gone wrong.
_instagramURL = [NSURL URLWithString:[NSString stringWithFormat: #"instagram://media?id=%#",[SingletoneClass sharedSingleTone].imageId]];
if ([[UIApplication sharedApplication] canOpenURL:_instagramURL]) {
self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]];
self.dic.delegate = self;
self.dic.UTI = #"com.instagram.exclusivegram";
self.dic.annotation = [NSDictionary dictionaryWithObject:[SingletoneClass sharedSingleTone].captionStr forKey:#"InstagramCaption"];
[self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ];
}
else {
UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:#"" message:#"Instagram is not present in your device" andCallback:^(id actionResponse) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[self presentViewController:alert animated:YES completion:nil];
}
If above code is correct, then please let me know, from where I can find the imageId?
Finally, I got the solution. We need to save the image in Document directory. Instagram app can retrieve the image from Document directory.
NSData *imagedata = UIImageJPEGRepresentation(image, 0.5);
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"insta.igo"]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imagedata attributes:nil]; //finally save the path (image)
Then by using UIDocumentInteractionController, we can share the image in Instagram app.
Before sharing the image, you need to be sure that Instagram app is present in the device.
- (void) shareImageToInstagram {
_instagramURL = [NSURL URLWithString:[NSString stringWithFormat: #"instagram://app"]];
if ([[UIApplication sharedApplication] canOpenURL:_instagramURL])
{
self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]];
self.dic.delegate = self;
self.dic.UTI = #"com.instagram.photo";
self.dic.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[SingletoneClass sharedSingleTone].captionStr,#"InstagramCaption", nil];
[self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ];
}
else
{
UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:#"" message:#"Instagram is not present in your device" andCallback:^(id actionResponse) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
You can refer the following links for more information.
https://www.instagram.com/developer/mobile-sharing/iphone-hooks/
and Share photo to Instagram from my iOS App
Check Below code for share image on Instagram , its working fine
import
-(void)shareImageOnInstagram:(UIImage *)image {
if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"instagram://"]]) {
//Your device doesn't have Instagram app.
return;
}
//__weak typeof(self) weakSelf = self;
__block PHFetchResult *photosAsset;
__block PHObjectPlaceholder *placeholder;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
placeholder = [createAssetRequest placeholderForCreatedAsset];
photosAsset = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:#[placeholder.localIdentifier] options:nil];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.synchronous = YES;
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
NSString *identifier = placeholder.localIdentifier;
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:#"instagram://library?LocalIdentifier=%#",identifier]];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[[UIApplication sharedApplication] openURL:instagramURL options:#{} completionHandler:^(BOOL success) {
}];
}
});
}
}];
}
Hi in my application I have a file in URL I want download to my document folder in my application while downloading the file i want to show the progress bar. So I have used the MBProgressHUD for that but its not working properly its showing late please tell me how to resolve this one.
My code:
- (IBAction)down:(id)sender {
UIButton *btn = (UIButton *)sender;
spinner = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
spinner.mode = MBProgressHUDModeCustomView;
[spinner setLabelText:#"downloading....."];
[spinner setLabelFont:[UIFont systemFontOfSize:15]];
[spinner show:YES];
NSURL *url = [NSURL URLWithString:fileurl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
}
[activityIndicatorObject stopAnimating];
[spinner hide:YES];
[spinner removeFromSuperViewOnHide];
}
I have used the above code its taking too much time to show the MBProgressHUD Please tell me how to resolve this issue I have stuck here for time.
Thanks..
You have to change in your code as below..
- (IBAction)down:(id)sender {
UIButton *btn = (UIButton *)sender;
//spinner = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
//spinner.mode = MBProgressHUDModeCustomView;
//[spinner setLabelText:#"downloading....."];
//[spinner setLabelFont:[UIFont systemFontOfSize:15]];
//[spinner show:YES];
NSURL *url = [NSURL URLWithString:fileurl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
}
//[activityIndicatorObject stopAnimating];
//[spinner hide:YES];
//[spinner removeFromSuperViewOnHide];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
Enjoy Code..
I suspect what you are experiencing are concurrency issues with the above code. I'm assuming the URL you are fetching is from over a network. The NSData method dataWithContentsOfURL: is blocking the main thread before the operating system has a chance to call setNeedsDisplay on the spinner, which also happens on the main thread, and this could explain why it's showing up late.
The solution would be to make some sort of asynchronous request, to fetch the file, with a completion handler, so your application can do tasks etc upon completion, (like stopping the activity indicator, persisting the file to local storage etc).
This is what the documentation has has to say about the dataWithContentsOfURL: of NSData class :-
Important: Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSSession class.
Im using this tutorial to load an image asynchronously in my app. I modified that code so the picture saves to the iPhone's local files and can be loaded while offline. I want to make it so this load request times out after a certain interval, possibly 15-20 seconds, and loads the saved file instead of downloading a new one. I found ways to make a web view time out, but Im not sure how to go about doing this using the asynchronous method. How can I make a timeout request for the way that this code loads the url?
Thanks
Edit: I want to make it time out if it is unable to connect to the website and also if the downloading of the picture takes too long.
- (void)viewDidLoad
{
[super viewDidLoad];
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:#selector(loadImage)
object:nil];
[queue addOperation:operation];
}
- (void)loadImage {
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.TestURL.com/test.jpg"]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"test.jpg"]];
[imageData writeToFile:localFilePath atomically:YES];
[self performSelectorOnMainThread:#selector(displayImage:) withObject:image waitUntilDone:YES];
}
if you use NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.TestURL.jpg"]]; You are creating a synchronous connection, so You canĀ“t cancel it. You need to wait till the end.
You should implement an asynchronous download using NSURLConnection as explained in How can I deal with connection problem when I use NSData?
Now, I am a newbie at this to, and I realize that this is a way to do it but really doesn't answer the question, but how I handled this situation was to write a method that first checked locally for the image, and if it wasn't there, load it from the web and save it locally, so it was there the next time. Here is some code.
- (UIImage *)checkForLocalImageThenSave:(NSString *)name fromStringURL:(NSString *)url {
NSLog(#"********** Start loading image **********\n\n");
UIImage *image = [[UIImage alloc] init];
NSString *localDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *profilePicName = [NSString stringWithFormat:#"/%#", name];
NSString *profilePicNameOnline = [NSString stringWithFormat:#"%#", url];
NSString *directoryWithProfilePicName = [localDirectory stringByAppendingString:profilePicName];
NSLog(#"Looking for file: %#", directoryWithProfilePicName);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:directoryWithProfilePicName];
if (fileExists) {
NSLog(#"File exists. Load: %#\n\n", directoryWithProfilePicName);
image = [[UIImage alloc] initWithContentsOfFile: directoryWithProfilePicName];
NSLog(#"********** Loading image done **********\n\n");
} else {
NSLog(#"File does not exist. Save: %#", directoryWithProfilePicName);
// TO SAVE A JPEG FILE
NSData *imageWithURL = [[NSData alloc] initWithContentsOfURL:[[NSURL alloc] initWithString:profilePicNameOnline]];
NSLog(#"File at? %#", profilePicNameOnline);
image = [[UIImage alloc] initWithData:imageWithURL];
NSString *jpegFilePath = directoryWithProfilePicName;
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data writeToFile:jpegFilePath atomically:YES];
NSLog(#"Saving image done.");
}
return image;
}
I want to convert an android app to iPhone. I managed to get the contents of a server by,
NSString *s =[NSString stringWithFormat:#"www.xyz.com"];
NSURL *url = [NSURL URLWithString:s];
// NSLog(s);
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
But, how to get the progress dialog with rotating spinner till it loads. Kindly help and oblige.
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeAnnularDeterminate;
hud.labelText = #"Loading";
[self doSomethingInBackgroundWithProgressCallback:^(float progress) {
hud.progress = progress;
} completionCallback:^{
[hud hide:YES];
}];
you have add this code
download source from https://github.com/jdg/MBProgressHUD