Cannot load files in UIDocumentInteractionController - objective-c

I am building an app that allows the opening of a PDF, and handles this like so:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url sourceApplication:(NSString *)source annotation:(id)annotation
{
if (url != nil && [url isFileURL])
{
if ([[url pathExtension] isEqualToString:#"pdf"])
{
FilePreviewViewController *filePreviewController = [[FilePreviewViewController alloc] init];
[filePreviewController setURL:url];
[self.navController pushViewController:filePreviewController animated:NO];
return YES;
}
}
return NO;
}
And then in FilePreviewController.m:
-(void) setURL:(NSURL *) URL
{
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentPreviewAnimated:NO];
}
However, when I open a file and the view transitions, I get these messages:
Unbalanced calls to begin/end appearance transitions for <QLRemotePreviewContentController: 0x1581fe00>.
Couldn't issue file extension for path: /private/var/mobile/Containers/Data/Application/6399D00B-47A1-4F33-B34C-3F0B07B648AE/Documents/Inbox/pdf-8.pdf
And the file itself does not load. I'm not sure what I'm doing wrong because this works fine on the simulator (i.e. the PDF loads and displays perfectly).

use this code to view/read pdf format file.
.h
<UIDocumentInteractionControllerDelegate>
UIDocumentInteractionController *controller;
.m
NSString *File_name=[NSString stringWithFormat:#"%#",URL];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",docDir,[File_name lastPathComponent]];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:URL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (pdfData) {
[pdfData writeToFile:pngFilePath atomically:YES];
controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:pngFilePath]];
controller.delegate = self;
CGRect rect = CGRectMake(0, 0, appDelegate.wVal, appDelegate.hVal);
[controller presentOptionsMenuFromRect:rect inView:self.view animated:YES];
}
});
});

Related

How to login With instagram and share wtih instagram Using IOS ? Objective c

1) Register to Instagram
To create Application using the Instagram API, you must have an account with Instagram.
After creating your account in Instagram, login with Instagram account and open the URL: http://instagram.com/developer/
Go to “Register your application” and click on the “Register New Client” button.
You will be asked to provide Application Name, Description of your application, website and oAuth redirect_url. Here, the oAuth redirect_url specifies where to redirect users after they have chosen whether or not to authenticate your application.
After successfully registering new client, Instagram will provide CLIENT INFO like CLIENT ID, CLIENT SECRET, WEBSITE URL, REDIRECT URI. Save CLIENT ID,CLIENT SECRET, REDIRECT URI to your application constants class as you will need this for authenticating to Instagram.
Lets see how can we authenticate…
Step 1.
At First set the authentication URL
Create a header file and provide the header file name is ConstantHandle
and set the all authentication URL
#ifndef ConstantHandler_h
#define ConstantHandler_h
//set User authentication and url
#define INSTAGRAM_AUTHURL #"https://api.instagram.com/oauth/authorize/"
#define INSTAGRAM_APIURl #"https://api.instagram.com/v1/users/"
#define INSTAGRAM_CLIENT_ID #"Client Id"
#define INSTAGRAM_CLIENTSERCRET #"Clients Secret"
#define INSTAGRAM_REDIRECT_URL #"Redirect URL"
#define INSTAGRAM_ACCESS_TOKEN #"access_token"
#define INSTAGRAM_SCOPE   #"likes+comments+relationships+basic"
//Contant Url
#define ACCESS_TOKEN #"#access_token="
#define UNSIGNED #"UNSIGNED"
#define CODE #"code="
#define END_POINT_URL #"https://api.instagram.com/oauth/access_token"
#define HTTP_METHOD #"POST"
#define CONTENT_LENGTH #"Content-Length"
#define REQUEST_DATA #"application/x-www-form-urlencoded"
#define CONTENT_TYPE #"Content-Type"
//share Photo Constant
#define DOCUMENT_FILE_PATH #"Documents/originalImage.ig"
#define APP_URL #"instagram://app"
#define UTI_URL #"com.instagram.exclusivegram"
#define MESSAGE #"Instagram not installed in this device!\nTo share image please install instagram."
#endif /* ConstantHandler_h */
At first set the all micro
Step 2.
Add a file in your project
Provide the file name is
InstagramController
create a file inherit with UIViewController
Add the this code in InstagramController.h file
#import <UIKit/UIKit.h>
#import "ConstantHandler.h"
#interface InstagramController : UIViewController
- (void)loginWithInstagramWithParsentViewController:(UIViewController *)controller completionHandler:(void(^)(NSDictionary *userProfileInformation))completionHanlder failureHandler:(void(^)(NSDictionary *errorDetail))failureHandler;
- (void)sharePhotoWithInstagaramWithImage:(UIImage *)image parsentViewcontroller:(UIViewController *)controller;;
#end
Add the this code in InstagramController.m file
#import "InstagramController.h"
#interface InstagramController ()<UIWebViewDelegate,UIDocumentInteractionControllerDelegate>
{
UIView *_progressView;
UIWebView *_webView;
UIViewController *_controller;
UIActivityIndicatorView *_activitiyIndicator;
}
#property(strong,nonatomic)NSString *typeOfAuthentication;
#property (nonatomic, strong) void(^completionHandler)(NSDictionary *);
#property (nonatomic, strong) void(^failureHandler)(NSDictionary *);
#property(nonatomic,strong)UIDocumentInteractionController *docFile;
#end
#pragma mark - View Controller Life Cycle Method
#implementation InstagramController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
//Add the cancel Button
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 70, 20)];
[button setTitle:#"Cancel" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//Setup The UIWebView
[super viewDidAppear: animated];
_webView = [UIWebView new];
CGRect frame = self.view.frame;
frame.origin.y = 64;
_webView.frame = frame;
_webView.delegate = self;
[self.view addSubview:_webView];
//Hit instagaram API;
NSString* authURL = nil;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
if ([_typeOfAuthentication isEqualToString:UNSIGNED])
{
authURL = [NSString stringWithFormat: #"%#?client_id=%#&redirect_uri=%#&response_type=token&scope=%#&DEBUG=True",
INSTAGRAM_AUTHURL,
INSTAGRAM_CLIENT_ID,
INSTAGRAM_REDIRECT_URL,
INSTAGRAM_SCOPE];
}
else
{
authURL = [NSString stringWithFormat: #"%#?client_id=%#&redirect_uri=%#&response_type=code&scope=%#&DEBUG=True",
INSTAGRAM_AUTHURL,
INSTAGRAM_CLIENT_ID,
INSTAGRAM_REDIRECT_URL,
INSTAGRAM_SCOPE];
}
[_webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: authURL]]];
}
#pragma mark - Local Method
/*!
Setup The genral Indicator View
#retur void
*/
- (void)addIndicatorView {
_progressView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 62)];
_progressView.layer.cornerRadius = 10;
_progressView.layer.masksToBounds = YES;
_progressView.backgroundColor = [UIColor blackColor];
_progressView.alpha = 0.7;
UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10,43, 80, 15)];
lable.textColor = [UIColor grayColor];
[lable setTextAlignment:NSTextAlignmentCenter];
lable.font = [UIFont italicSystemFontOfSize:15.0f];
lable.text = #"progress...";
[_progressView addSubview:lable];
_activitiyIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[_activitiyIndicator setCenter:CGPointMake(_progressView.frame.size.width/2.0, _progressView.frame.size.height/2.3)]; // I do this because I'm in landscape mode
[_progressView addSubview:_activitiyIndicator];
[_activitiyIndicator startAnimating];
_progressView.center = self.view.center;
[_webView addSubview:_progressView];
}
/*!
This method is used to request to call back Url and check the authenTication
#param NSURLRequest is the check the request URl;
#return BOOLk
*/
- (BOOL) checkRequestForCallbackURL: (NSURLRequest*) request
{
NSString* urlString = [[request URL] absoluteString];
if ([_typeOfAuthentication isEqualToString:UNSIGNED])
{
// check, if auth was succesfull (check for redirect URL)
if([urlString hasPrefix: INSTAGRAM_REDIRECT_URL])
{
// extract and handle access token
NSRange range = [urlString rangeOfString: ACCESS_TOKEN ];
[self handleAuth:[urlString substringFromIndex: range.location+range.length] withProfileInfo:nil];
return NO;
}
}
else
{
if([urlString hasPrefix: INSTAGRAM_REDIRECT_URL])
{
// extract and handle code
NSRange range = [urlString rangeOfString: CODE];
[self makePostRequest:[urlString substringFromIndex: range.location+range.length]];
return NO;
}
}
return YES;
}
/*!
This method is used to get the User profile information
#param NSString is a authToken
#return void;
*/
-(void)makePostRequest:(NSString *)authToken
{
NSString *post = [NSString stringWithFormat:#"client_id=%#&client_secret=%#&grant_type=authorization_code&redirect_uri=%#&code=%#",INSTAGRAM_CLIENT_ID,INSTAGRAM_CLIENTSERCRET,INSTAGRAM_REDIRECT_URL,authToken];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:END_POINT_URL];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *requestData = [NSMutableURLRequest requestWithURL:url];
requestData.HTTPMethod = HTTP_METHOD;
[requestData setValue:postLength forHTTPHeaderField:CONTENT_LENGTH];
[requestData setValue:REQUEST_DATA forHTTPHeaderField:CONTENT_TYPE];
requestData.HTTPBody = postData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:requestData
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (!error)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self handleAuth:[dictionary valueForKey:#"access_token"] withProfileInfo:dictionary];
} else{
NSLog(#"Error: %#", error.localizedDescription);
[self handleAuth:nil withProfileInfo:nil];
}
}];
// Start the task.
[task resume];
}
/*!
This method is used to get The profile information is the request is completed
#param NSSTring authetication key
#return void
*/
- (void) handleAuth: (NSString*)authToken withProfileInfo:(NSDictionary *)dictionary
{
NSLog(#"successfully logged in with Tocken == %#",authToken);
if (dictionary) {
_completionHandler(dictionary);
} else _failureHandler(dictionary);
// [self makePostRequest:authToken];
[self cancelLogin];
}
- (void)cancelLogin {
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *vc = [_controller.childViewControllers lastObject];
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
});
}
#pragma mark -WebView Delegate Method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
return [self checkRequestForCallbackURL: request];
}
- (void) webViewDidStartLoad:(UIWebView *)webView
{
[self addIndicatorView];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[_progressView removeFromSuperview];
_progressView = nil;
[_activitiyIndicator stopAnimating];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self webViewDidFinishLoad: webView];
}
#pragma mark - user Define Method
- (void)loginWithInstagramWithParsentViewController:(UIViewController *)controller completionHandler:(void(^)(NSDictionary *userProfileInformation))completionHanlder failureHandler:(void(^)(NSDictionary *errorDetail))failureHandler {
_controller = controller;
[controller addChildViewController:self];
self.view.frame = controller.view.frame;
[controller.view addSubview:self.view];
[self didMoveToParentViewController:controller];
_completionHandler = completionHanlder;
_failureHandler = failureHandler;
}
- (void)sharePhotoWithInstagaramWithImage:(UIImage *)image parsentViewcontroller:(UIViewController *)controller{
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:DOCUMENT_FILE_PATH];
if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
NSFileManager *fielManager = [NSFileManager defaultManager];
[fielManager removeItemAtPath:savePath error:nil];
}
BOOL save = [UIImagePNGRepresentation(image) writeToFile:savePath atomically:YES];
NSURL *instagramURL = [NSURL URLWithString:APP_URL];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL] && save) {
self.docFile = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
self.docFile.UTI = UTI_URL;
self.docFile.delegate = self;
[self.docFile presentOpenInMenuFromRect:CGRectZero inView:controller.view animated:YES];
} else {
NSLog(#"%#",MESSAGE);
}
}
#pragma mark - UIDocumentInteractionController delegateMethod
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
#pragma mark - selector method
-(void)cancel:(UIButton *)button {
[self cancelLogin];
}
#end
Step 3:
Finally import "ConstantHandler.h" file in ViewController
Add the Login and share Button in ViewController and the this code
#import "ViewController.h"
#import "InstagramController.h"
#interface ViewController ()
#property(nonatomic,strong) InstagramController *instagramHandler ;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)loginWithInstagram:(id)sender {
_instagramHandler = [InstagramController new];
[_instagramHandler loginWithInstagramWithParsentViewController:self completionHandler:^(NSDictionary *userProfileInformation) {
NSLog(#"%#",userProfileInformation);
} failureHandler:^(NSDictionary *errorDetail) {
NSLog(#"%#",errorDetail);
}];
}
- (IBAction)shareWithInstagram:(id)sender {
_instagramHandler = [InstagramController new];
UIImage *image = [UIImage imageNamed:#"flower-197343_960_720.jpg"];
[_instagramHandler sharePhotoWithInstagaramWithImage:image parsentViewcontroller:self];
}
#end
Step 4.
Build and run the project
Delete NSHTTPCookieStorage and Use App Transport Security.
And add webView delegate before webView request. After use method, dealloc and set webView delegate to nil.

how to share image on instagram from native app ios 9.2?

i have tried this code but it shows error like
Warning: Attempt to present <_UIDocumentActivityViewController:
0x16acdc00> on which is already
presenting <_UIDocumentActivityViewController: 0x16ae4800>
how to solve this??
-(IBAction)saveToInstagram:(id)sender {
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.ig"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
NSLog(#"JPG path %#", jpgPath);
NSLog(#"URL Path %#", igImageHookFile);
self.docFile.UTI = #"com.instagram.photo";
self.docFile = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.docFile=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://media?id=MEDIA_ID"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
}
else {
NSLog(#"No Instagram Found");
}
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller {
}
The problem is that while the first docfile is being presented you try to present the second one
// First presentation
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://media?id=MEDIA_ID"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
// Second presentation
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
}
I don't really understand why do you need to use the same method twice, but if you really do, then for the first presentation use animated: NO. I would suggest some kind of completion code block, but it appears that there is no such method for UIDocumentInteractionController
Don't forget to add instagram in you plist array with key: LSApplicationQueriesSchemes.
#property (nonatomic, strong) UIDocumentInteractionController *docIC;
- (void)sharePhoto:(UIImage *)image caption:(NSString *)caption
{
NSURL *instagramURL = [NSURL URLWithString:#"instagram://"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
NSString *imgPath = [TUtil documentPath:#"Image.igo"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:imgPath atomically:YES];
NSURL *igImageHookFile = [NSURL fileURLWithPath:imgPath];
self.docIC = [UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.docIC setDelegate:self];
[self.docIC setUTI:#"com.instagram.exclusivegram"];
// Subject
[self.docIC setName:[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"]];
//http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing
//self.docIC.annotation = [NSDictionary dictionaryWithObjectsAndKeys:caption, #"InstagramCaption", nil];
[self.docIC presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
else
{
NSString *iTunesLink = #"itms-apps://itunes.apple.com/app/id389801252?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
}
}

Which third party Imageview class should i used?

My requirement is :
Need to show image in imageview from server URL & save it for offline use also.
But There may be chances that same URL image can be updated.
I tried EGOImageview,AsyncImageview,FXImageview,Haneke thsese all classes i tried.
my first part of requirement is achieved. but not second..i.e if "xxxxx" link image is shown for first time....if on that same link image is upadated ,app shows old image only...
You can use the below class that will full fill your requirement
DImageView.h
#import <UIKit/UIKit.h>
#interface DImageView : UIImageView
#property (nonatomic, strong) UIActivityIndicatorView *activityView;
- (void)processImageDataWithURLString:(NSString *)urlString;
+ (UIImage *)getSavedImage :(NSString *)fileName;
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData;
DImageView.m
#import "DImageView.h"
#define IMAGES_FOLDER_NAME #"DImages"
#implementation DImageView
#pragma mark - App Life Cycle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (void)dealloc
{
self.activityView = nil;
[super dealloc];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initWithFrame:[self frame]];
}
return self;
}
#pragma mark - Download images
- (void)processImageDataWithURLString:(NSString *)urlString //andBlock:(void (^)(UIImage * img))processImage
{
#autoreleasepool
{
UIImage * saveImg = [DImageView getSavedImage:urlString];
if (saveImg)
{
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_async(callerQueue, ^{
#autoreleasepool
{
[self setImage:saveImg];
}
});
}
else
{
[self showActivityIndicator];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
__block NSError* error = nil;
dispatch_async(downloadQueue, ^{
NSData * imageData = [[[NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error] retain] autorelease];
if (error)
{
NSLog(#"DImg Error %#", [error debugDescription]);
}
else
{
dispatch_async(callerQueue, ^{
#autoreleasepool
{
UIImage *image = [UIImage imageWithData:imageData];
[self setImage:image];
[self hideActivityIndicator];
/* Below code is to save image*/
[DImageView saveImageWithFolderName:IMAGES_FOLDER_NAME AndFileName:urlString AndImage:imageData];
}
});
}
});
dispatch_release(downloadQueue);
}
}
}
#pragma mark - File Save methods
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData
{
#autoreleasepool
{
NSFileManager *fileManger = [NSFileManager defaultManager] ;
NSString *directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],folderName] ;
if (![fileManger fileExistsAtPath:directoryPath])
{
NSError *error = nil;
[fileManger createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
}
fileName = [DImageView fileNameValidate:fileName];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
BOOL isSaved = [imageData writeToFile:filePath atomically:YES];
if (!isSaved)
{
NSLog(#" ** Img Not Saved");
}
}
}
+ (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
+ (UIImage *)getSavedImage :(NSString *)fileName
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
fileName = [DImageView fileNameValidate:fileName];
NSFileManager * fileManger = [NSFileManager defaultManager] ;
NSString * directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],IMAGES_FOLDER_NAME] ;
NSString * filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
if ([fileManger fileExistsAtPath:directoryPath])
{
UIImage *image = [UIImage imageWithContentsOfFile:filePath] ;
if (image)
{
return image;
}
else
{
NSLog(#"** Img Not Found **");
return nil;
}
}
[pool release];
return nil;
}
+ (NSString*) fileNameValidate : (NSString*) name
{
name = [name stringByReplacingOccurrencesOfString:#"://" withString:#"##"];
name = [name stringByReplacingOccurrencesOfString:#"/" withString:#"#"];
name = [name stringByReplacingOccurrencesOfString:#"%20" withString:#""];
return name;
}
#pragma mark - Activity Methods
- (void) showActivityIndicator
{
self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
self.activityView.hidesWhenStopped = TRUE;
self.activityView.backgroundColor = [UIColor clearColor];
self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self addSubview:self.activityView];
[self.activityView startAnimating];
}
- (void) hideActivityIndicator
{
CAAnimation *animation = [NSClassFromString(#"CATransition") animation];
[animation setValue:#"kCATransitionFade" forKey:#"type"];
animation.duration = 0.4;;
[self.layer addAnimation:animation forKey:nil];
[self.activityView stopAnimating];
[self.activityView removeFromSuperview];
for (UIView * view in self.subviews)
{
if([view isKindOfClass:[UIActivityIndicatorView class]])
[view removeFromSuperview];
}
}
What will this class do ?
It will download images from server and save it to application document directory And get it from local if its available.
How to use that ?
Set DImageView class in your nib file for UIImageView.
Then you can simply use it as below in your .m file.
[imgViewName processImageDataWithURLString:imageURl];
You should take a look at SDWebImage. It's one of the most used UIImageView category right now and offers a lot of features, including caching.
Have a look at this part of the documentation to learn how to refresh your cache with it: Handle image refresh

MPMoviePlayerController endless loading (filepicker)

I am trying to stream a video uploaded on filepicker, but it keeps loading without playing the video.
The link is: https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv
The page is a video/mp4 page, but as you can see there is no extension for the page.
The Code:
#interface RTVideo()
#property (nonatomic,strong) MPMoviePlayerController *moviePlayer;
#end
#implementation RTVideo
UIView *frame;
-(void)play
{
NSNumber *adId = 5 ;
NSString *session = [[NSUserDefaults standardUserDefaults]stringForKey:#"sessionID"];
NSString *type = #"video";
[NetworkManagerCenter retrievePageWithtype:type
Id:adId
session:session
success:^(RT *ad) {
[self playAD];
} failure:^(NSError *error) {
[self removeFromSuperview];
}];
}
-(void)playAD
{
frame = self;
NSURL *movieURL = [NSURL URLWithString: #"https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[frame addSubview:self.moviePlayer.view];
self.moviePlayer.fullscreen = YES;
self.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
self.moviePlayer.initialPlaybackTime = -1.0;
[self.moviePlayer prepareToPlay];
[self.moviePlayer play];
}
#end
Is this not working because there is no extension and how can I solve this?

Page View Controller: UILabel and UIImageview empty on first page

I'm using a UIPageViewController to display items from a JSON file. It works fine except for the first page which displays nothing on loading, but if I come back, it works.
Code is as follows:
#import "SJPagesViewController.h"
#import "SJChildViewController.h"
#interface SJPagesViewController ()
#end
#implementation SJPagesViewController
#synthesize urlToFollow, data,articlesArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
...
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
CGFloat window_height = ([self window_height]-30.0);
CGFloat window_width = [self window_width];
CGRect pageFrame = CGRectMake(0.0f, 0.0f,window_width , window_height);
self.pageController.dataSource = self;
[[self.pageController view] setFrame:pageFrame];
SJChildViewController *initialViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:self.pageController];
[[self view] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
//Download JSON
NSError *error=nil;
NSURL *url = [NSURL URLWithString:urlToFollow];
data = [NSData dataWithContentsOfURL: url options:NSDataReadingMappedIfSafe error:&error];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *response = [dictionary objectForKey:#"items"];
articlesArray = [[NSArray alloc] initWithArray:response];
//NSLog(#"articlesArray = %#", articlesArray);
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSUInteger index = [(SJChildViewController *)viewController index];
if (index == 0) {
return nil;
}
index--;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
NSUInteger index = [(SJChildViewController *)viewController index];
index++;
if (index == articlesArray.count) {
return nil;
}
return [self viewControllerAtIndex:index];
}
- (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
- (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (SJChildViewController *)viewControllerAtIndex:(NSUInteger)index {
SJChildViewController *childViewController = [[SJChildViewController alloc] initWithNibName:#"SJChildViewController" bundle:nil];
childViewController.index = index;
childViewController.arrayCount = self.articlesArray.count;
childViewController.model = [[self.articlesArray objectAtIndex:index]objectForKey:#"modelo"];
childViewController.price = [[self.articlesArray objectAtIndex:index]objectForKey:#"precio"];
childViewController.make = [[self.articlesArray objectAtIndex:index]objectForKey:#"marca"];
childViewController.imageUrl = [[self.articlesArray objectAtIndex:index]objectForKey:#"photoUrl"];
return childViewController;
}
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController {
// The number of items reflected in the page indicator.
if (articlesArray.count >5) {
return 5;
}else return [articlesArray count];
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
// The selected item reflected in the page indicator.
return 0;
}
#end
And ChildViewController to display items:
#implementation SJChildViewController
#synthesize activityIndicator,imageUrl,price,model,make;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
....
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Activity indicator
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
[self.view addSubview: activityIndicator];
[activityIndicator startAnimating];
}
-(void)viewDidAppear:(BOOL)animated{
self.scrrenNumber.text = [NSString stringWithFormat:#"Artículo %ld de %ld", ((long)self.index+1), (long)self.arrayCount];
self.lblMake.lineBreakMode = NSLineBreakByWordWrapping;
self.lblMake.text = [NSString stringWithFormat:#"%#",make];
//Donload image
//Download image from url
NSURL *url_1= [NSURL URLWithString:imageUrl];
NSURLRequest *request_1 = [NSURLRequest requestWithURL:url_1];
[NSURLConnection sendAsynchronousRequest:request_1
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
UIImage *img = [UIImage imageWithData:data];
[self.articleImage performSelectorOnMainThread:#selector(setImage:) withObject:img waitUntilDone:YES];
}];
//Activity indicator
self.lblPrice.text = [NSString stringWithFormat:#"%#",price];
self.lblModel.lineBreakMode = NSLineBreakByWordWrapping;
self.lblModel.text = [NSString stringWithFormat:#"%#",model];
[activityIndicator stopAnimating];
}
How can I make it work from the first moment?
Luis, I don't have access to xcode right now but it appears your issue is that you are instantiating childViewController while articlesArray is empty.
In viewDidLoad you are downloading your json file and populating articlesArray after you call your helper method viewControllerAtIndex.
Try downloading your json file and populating the array first like you have here.
//Download JSON
NSError *error=nil;
NSURL *url = [NSURL URLWithString:urlToFollow];
data = [NSData dataWithContentsOfURL: url options:NSDataReadingMappedIfSafe error:&error];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *response = [dictionary objectForKey:#"items"];
articlesArray = [[NSArray alloc] initWithArray:response];
Then create your pageViewController and populate it like you did here.
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
CGFloat window_height = ([self window_height]-30.0);
CGFloat window_width = [self window_width];
CGRect pageFrame = CGRectMake(0.0f, 0.0f,window_width , window_height);
self.pageController.dataSource = self;
[[self.pageController view] setFrame:pageFrame];
SJChildViewController *initialViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:self.pageController];
[[self view] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];