Facebook in iPhone app - iphone

I am working on an iPhone app,in this i have an option for sharing my posts with face book(i am just passing the user id of facebook user and my server side developer do the posting part)
I am able to take the user id while log in in face book
But problem is-after the user authenticate from facebook,"post on your behalf" is not coming in the app
(i am using ios6 SDK)
(i have created my app in facebook with checked that public_action from graph)
I have gone through the tutorials(scrumptious) given in facebook developer page,but could not make it
Here are my code-If any one find the error or missing part,please help me to clear that
AppDelegate.h
#import <FacebookSDK/FacebookSDK.h>
#class ViewController;
#interface AppDelegate : UIResponder
#property (strong, nonatomic) FBSession *session;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#property (strong,nonatomic) IBOutlet UINavigationController *navBar;
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#define APP_ID #"fd725FDE45a44198a5b8ad3f7a0ffa09"
#implementation AppDelegate
#synthesize session = _session;
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [self.session handleOpenURL:url];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_location",
#"user_birthday",
#"user_likes",
#"email",
#"publish_action",
nil];
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
default:
break;
}
}
#end
InviteFriendViewController.h
#interface InviteFriendViewController :
-(IBAction)fbfrnds:(id)sender;
- (void)updateView;
#end
InviteFriendViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"userid"];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (!appDelegate.session.isOpen) {
appDelegate.session = [[FBSession alloc] init];
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}
];
}
}
}
-(void)facebookReteriveInformation:(NSDictionary *)dictnry{
FriendlistViewController *friends = [[FriendlistViewController alloc]initWithNibName:#"FriendlistViewController" bundle:nil];
friends.token = string;
[self.navigationController pushViewController:friends animated:YES];
}
-(IBAction)fbfrnds:(id)sender{
sharedClass=[SharedClass sharedInstance];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[self updateView];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}];
}
NSLog(#"string issss %#",string);
}
- (void)updateView {
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSLog(#"string issss %#",string);
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
} else {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
}
}
-(void)dataFetching:(NSString*)strng1{
NSURL *url = [NSURL URLWithString:strng1];
ProfileConnector *obj = [[ProfileConnector alloc] init];
obj.delegate1 = self;
[obj parsingJson:url];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
} else {
action();
}
}
}
#end

Since you're using the 3.1 version of Facebook SDK, openActiveSessionWithPermissions:allowLoginUI:completionHandler: is not supposed to be used and the old way of doing it does not seem to be functional anymore; from the 3.1 migration documentation;
...you will need to remove usage of openActiveSessionWithPermissions:allowLoginUI:completionHandler: and replace it with openActiveSessionWithReadPermissions:allowLoginUI:completionHandler: (or even more simply, openActiveSessionWithAllowLoginUI).
Later, when your app needs to publish back to Facebook, you should use reauthorizeWithPublishPermissions:defaultAudience:completionHandler: to seek the additional permissions.
Even more details available at the migration docs.

Related

Post to Facebook not working from delegate

I have added FBSdk in my project along with SBJson classes, what files should i import in my second view controller to work my code ?
I want to post on Fb using the description under url so for that i need to include this code into my second view controller, but i am stuck in a part i founded that the below code should be added in the second view controller but the "delegate:self" not works, as i am doing this first time so can any one guide me how should i code in my second view controller keeping into account the values from the app delegate (How should i get the values from the app delegate of FB to the second view so that i can add this code in second code plz can any one correct this code)
facebook = [[Facebook alloc] initWithAppId:#"YOUR_APP_ID"];
// how should i take this id from the app delegate ?
NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
NSMutableDictionary* params = [[NSMutableDictionary alloc]
initWithCapacity:1]
[params setObject:#"Testing" forKey:#"name"];
[params setObject:#"IMAGE_URL" forKey:#"picture"];
[params setObject:#"Description" forKey:#"description"];
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Is the above code correct ?
How should i implement it in my second view controller in -(void)fb_share (method).
My App Delegate File is Like this :
#import "AppDelegate.h"
#import "ViewController.h"
#import "ServerRequests.h"
#import "DBManager.h"
#import "SBJson.h"
#include "FBSession.h"
#import "FBRequest.h"
#import "FBGraphUser.h"
NSString *const FBSessionStateChangedNotification = #"com.myapp:FBSessionStateChangedNotification";
#implementation AppDelegate
#synthesize userId;
#synthesize dbSnyced;
#synthesize fbId;
#synthesize loginView;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ self.fbId = #"-1";
self.dbSnyced = NO;
self.loginView = nil;
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:self.viewController] autorelease];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
[self showLogin:NO];
}
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self checkAccountLogin];
}
- (void) applicationDidEnterBackground:(UIApplication *)application
{
[self hideLogin:NO];
}
- (void) applicationWillTerminate:(UIApplication *)application
{
NSLog(#"applicationWillTerminate");
[self hideLogin:NO];
[FBSession.activeSession close];
}
- (void) checkAccountLogin
{
self.dbSnyced = NO;
if([ServerRequests serverIsReachableAlertIfNo:YES]) {
DBManager *db = [[[DBManager alloc] initWithPath:DB_NAME] autorelease];
NSDictionary *userDic = [[db smartQueryForArrayWithStatement:#"SELECT * FROM table WHERE id=1"] objectAtIndex:0];
NSString *loginType = [userDic objectForKey:#"login_type"];
if([loginType isEqualToString:#"none"]) {
NSLog(#"no login type");
[self showLogin:NO];
}
else {
self.userId = [[userDic objectForKey:#"user_id"] intValue];
if([loginType isEqualToString:#"Facebook"]) {
NSLog(#"Facebook account");
[FBSession.activeSession handleDidBecomeActive];
}
else if([loginType isEqualToString:#"MyApp"]) {
NSLog(#"MyApp account");
}
}
}
}
#pragma - Fb stuff
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
NSLog(#"sessionStateChanged");
switch (state) {
case FBSessionStateOpen:
if (!error) {
[self handleFbUserDetails];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionStateChangedNotification object:session];
if (error) {
NSLog(#"error: %#", error.localizedDescription);
if(self.loginView) {
[self.loginView hideLoading];
}
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
// attempt to extract a token from the url
return [FBSession.activeSession handleOpenURL:url];
}
- (BOOL) activeFBSession
{
return FBSession.activeSession.isOpen;
}
- (void) closeFBSession
{
NSLog(#"closeFBSession");
[FBSession.activeSession closeAndClearTokenInformation];
}
- (void) showLogin:(BOOL)animated
{
if(!self.loginView) {
self.loginView = [[[LoginViewController alloc] init] autorelease];
[[self.navigationController topViewController] presentViewController:self.loginView animated:animated completion:nil];
}
}
- (void) hideLogin:(BOOL)animated
{
if(self.loginView) {
[self.viewController gotToTab:0];
[self.loginView hideLoading];
[[self.navigationController topViewController] dismissViewControllerAnimated:animated completion:^{
self.loginView = nil;
NSLog(#"self.loginView = nil");
}];
}
}
- (void) handleFbUserDetails
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"fb connected");
self.fbId = [user objectForKey:#"id"];
self.userId = -1;
ASIFormDataRequest *request = [ServerRequests ASIFormDataRequestForSrcipt:#"facebookUser"];
[request setPostValue:[user objectForKey:#"id"] forKey:#"fbId"];
[request setPostValue:user.first_name forKey:#"first_name"];
[request setPostValue:user.last_name forKey:#"last_name"];
[request setPostValue:user.location.name forKey:#"location"];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"facebookUser response: %#", response);
if([response rangeOfString:#"ERROR"].location == NSNotFound) {
self.userId = [response intValue];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
NSString *q = [NSString stringWithFormat:#"UPDATE table SET login_type = 'Facebook', user_id = '%#' WHERE id = 1", response];
NSLog(#"%#", q);
[db executeStatement:q];
[db release];
}
else {
}
[self sessionBecameActive];
}];
[request startAsynchronous];
[self hideLogin:YES];
}
else {
NSLog(#"error: %#", error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook Request Error" message:#"Cannot connect to Facebook." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
if(self.loginView) {
[self.loginView hideLoading];
}
}
[ServerRequests SyncDataBase];
}];
}
- (void) signOut
{
[self closeFBSession];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
[db executeStatement:#"UPDATE table SET login_type = 'none' WHERE id = 1"];
[db release];
[self showLogin:YES];
}
- (void) sessionBecameActive
{
[self.viewController sessionBecameActive];
}
#end
Can any one figure out what code should i write in the -(void)fb_share method in second view controller by getting values from the delegate ?
Any Help !
I did this ... and getting Error: HTTP status code: 400 ... but the user name get's displayed on alert
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
// NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
// #"publish_stream", nil];
// [facebook authorize:permissions delegate:self];
self.params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
#"https://developers.facebook.com/attachment/iossdk_logo.png", #"picture",
#"Facebook SDK for iOS", #"name",
#"Build great social apps and get more installs.", #"caption",
#"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps.", #"description",
nil];
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Upload to FB?"
message:[NSString stringWithFormat:#"Upload to ""%#"" Account?", user.name]
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"No",#"Yes", nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"PostUploaded"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
[tmp release];
}
}];
[tmp show];
[tmp release];
}
}];
.. what should i do now ?
declare facebook as a property in .h file of your appDelegate
then in second view controller import AppDelegate
in .m file where you want the Facebook object
get it like
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
Facebook *facebook = appDelegate.facebook;

facebook integration in iphone with Facebook sdk for ios5 and 6

i have use FAcebook sdk 3.0 to integrate facebook.I have use sample code "HelloFacebookSample"
to post status.
I have change in Info.plist file with my AppId.
I have problem that show armv7s,armv7 architecture problem.I even solve out that by "Build Active Architecture Only "to YEs.
I have code that show button for login/logout for facebook
#import "HFViewController.h"
#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#interface HFViewController () <FBLoginViewDelegate>
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error;
#end
#implementation HFViewController
#synthesize shareStringFb;
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
- (void)viewDidLoad {
[super viewDidLoad];
// Create Login View so that the app will be granted "status_update" permission.
self.buttonPostStatus.enabled = YES;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
statusText.text=self.shareStringFb;
{
// if the session is closed, then we open it here, and establish a handler for state changes
}
}
-(IBAction)backClick:(id)sender
{
[self.view removeFromSuperview];
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
self.loggedInUser = nil;
[super viewDidUnload];
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// first get the buttons set for login mode
self.buttonPostStatus.enabled = YES;
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
// NSDictionary methods such as objectForKey to get values from the my json object
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
self.buttonPostStatus.enabled = NO;
}
// Post Status Update button handler
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
// Post a status update to the user's feed via the Graph API, and display an alert view
// with the results or an error.
NSString *message = [NSString stringWithFormat:#"Updating %#'s status at %#",
self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:self.shareStringFb
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}
// Post Photo button handler
it show one button with login/logout in simulator but when i test in device it doesn't show that button.
Please any one can tell me what is problem?Why it not show that?Is there any other way to integrate Fb in ios 5 and 6 both.
Use for
this facebook sdk (3.1) for iOS6
ViewController.h
#import <FacebookSDK/FacebookSDK.h>
{
NSDictionary *dictionary;
NSString *user_email;
NSString *accessTokan;
NSMutableDictionary *fb_dict;
}
- (IBAction)btn_loginwithfacebook:(id)sender;
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self btn_loginwithfacebook:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"picture,id,birthday,email,name,gender,username" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
//NSDictionary *dictionary;
if([result objectForKey:#"data"])
dictionary = (NSDictionary *)[(NSArray *)[result objectForKey:#"data"] objectAtIndex:0];
else
dictionary = (NSDictionary *)result;
//NSLog(#"dictionary : %#",dictionary);
user_email = [dictionary objectForKey:#"email"];
[dictionary retain];
//NSLog(#"%#",user_email);//
}
}
}];
accessTokan = [[[FBSession activeSession] accessTokenData] accessToken];
//NSLog(#"%#",accessTokan);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",accessTokan]]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",str);
fb_dict = [str JSONValue];
[str release];}
FacebookAppID ::370546396320150
URL types
Item 0
URL Schemes
Item 0 ::fb370546396320150

Application continues to run when the device is connected to XCODE and debug mode. But it will not continue when it is not connected to xcode

I am creating a application that will continue running on back ground.
When the device is connected to the MAC and debugging, but when I disconnect and run the application standalone, it will finish in 10min. Is there any setting or my codings are wrong?
My code is appdeledate.h is
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
#class TashouNoEnViewController;
#interface TashouNoEnAppDelegate : NSObject <UIApplicationDelegate,GKSessionDelegate,GKPeerPickerControllerDelegate> {
UIWindow *window;
TashouNoEnViewController *viewController;
GKSession *mySession;
IBOutlet UITextField *messageTextField;
UIBackgroundTaskIdentifier backgroundTaskIdentifer;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet TashouNoEnViewController *viewController;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#end
appdelegate.M is
#import "TashouNoEnAppDelegate.h"
#import "TashouNoEnViewController.h"
#define kSessionID #"_tashounoen"
#implementation TashouNoEnAppDelegate
#synthesize window;
//=_window;
#synthesize viewController;
#synthesize navigationController=_navigationController;
NSString *message102;
NSString* a_home_dir;
NSString* a_doc_dir;
NSString* a_path;
NSString *switchcheck;
NSInteger myselfint;
NSInteger swithchcheckint;
NSInteger runcount;
NSInteger runcount2;
NSInteger totalruncount;
UIBackgroundTaskIdentifier bgTask;
NSTimer *caallTimer;
NSTimer *caallTimer2;
NSString *message100;
NSString *message200;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/**
NSLog(#"applicationWillResignActive");
// NSLog(#"%s", __PRETTY_FUNCTION__);
UIApplication* app = [UIApplication sharedApplication];
NSAssert(backgroundTaskIdentifer == UIBackgroundTaskInvalid, nil);
backgroundTaskIdentifer = [app beginBackgroundTaskWithExpirationHandler:^{
// NSLog(#"expired!");
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTaskIdentifer != UIBackgroundTaskInvalid) {
[app endBackgroundTask:backgroundTaskIdentifer];
backgroundTaskIdentifer = UIBackgroundTaskInvalid;
}
});
}];
**/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
self.window.rootViewController = self.navigationController;
runcount=0;
totalruncount=0;
NSLog(#"applicationDidEnterBackground");
caallTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(CAALL2) userInfo:nil repeats:NO];
void (^handler)(void) = ^{
bgTask = UIBackgroundTaskInvalid;
};
bgTask = [application beginBackgroundTaskWithExpirationHandler:handler];
[application setKeepAliveTimeout:600 handler:^{
bgTask = [application beginBackgroundTaskWithExpirationHandler:handler];
[caallTimer invalidate];
caallTimer = nil;
caallTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(CAALL2) userInfo:nil repeats:NO];
}];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSLog(#"applicationWillEnterForeground");
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(#"applicationDidBecomeActive");
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(#"applicationWillTerminate");
}
- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
}
- (void)session:(GKSession *)session didFailWithError:(NSError *)error {
}
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
NSError *error;
if(![mySession acceptConnectionFromPeer:peerID error:&error]) {
} else {
}
}
-(void)CAALL2
{
[mySession disconnectFromAllPeers];
[mySession release];
mySession = nil;
mySession = [[GKSession alloc] initWithSessionID:kSessionID displayName:nil sessionMode:GKSessionModePeer];
mySession.delegate = self;
[mySession setDataReceiveHandler:self withContext:nil];
mySession.available = YES;
caallTimer = [NSTimer scheduledTimerWithTimeInterval:500 target:self selector:#selector(CAALL2) userInfo:nil repeats:NO];
// if (totalruncount<21){
// }
}
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
switch (state) {
case GKPeerStateAvailable:
NSLog(#"GKPeerStateAvailable");
[mySession connectToPeer:peerID withTimeout:31.0f];
break;
case GKPeerStateUnavailable:
break;
case GKPeerStateConnected:
[self btnSend:peerID];
break;
case GKPeerStateDisconnected:
break;
case GKPeerStateConnecting:
break;
default:
break;
}
}
- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context {
message100 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"frompeerid%#",peer);
// NSLog(#"get%#",message100);
int checkdata = [message100 intValue ];
if (checkdata==111)
{
message100 =#"111";
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:0];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.fireDate = notificationDate;
notification.timeZone = [NSTimeZone systemTimeZone];
notification.alertBody = message100;
[app scheduleLocalNotification:notification];
[notification release];
}
else if (checkdata==110)
{
message100 =#"110";
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:0];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.fireDate = notificationDate;
notification.timeZone = [NSTimeZone systemTimeZone];
notification.alertBody = message100;
[app scheduleLocalNotification:notification];
[notification release];
}
}
- (void) mySendDataToPeers:(NSData *) data:(NSString *)peerID
{
NSError* error = nil;
NSLog(#"senddata");
if (mySession)
NSLog(#"mypeerid%#",peerID);
[mySession sendData:data toPeers:[NSArray arrayWithObject:peerID] withDataMode:GKSendDataReliable error:&error];
if (error) {
NSLog(#"%#", error);
}
}
-(void) btnSend:(NSString *)peerID{
a_home_dir = NSHomeDirectory();
NSString* a_doc_dir = [a_home_dir stringByAppendingPathComponent:#"Documents"];
a_path = [a_doc_dir stringByAppendingPathComponent:#"userdata.plist"];
NSDictionary *plist2 = [NSDictionary dictionaryWithContentsOfFile:a_path];
switchcheck =[plist2 objectForKey:#"switchcheck"];
swithchcheckint = [switchcheck intValue];
if(swithchcheckint==1)
{
message102 =#"111";
}
else if(swithchcheckint==0)
{
message102 =#"110";
}
//---convert an NSString object to NSData---
NSData* data;
[messageTextField setText:message102];
data = [message102 dataUsingEncoding:NSUTF8StringEncoding];
[self mySendDataToPeers:data:peerID];
}
#end
Please someone help.
Apple only allow background processing of an app to occur for 10 minutes (this used to be just 5), unless the app is either music, VOIP or navigational, in which case you will need to specify in your Plist file.
This is why you app stops after 10 minutes, by default Xcode will continue running the app as you are debugging.

Login ID and Password using core data iOS

I am creating doing a project with core data.
Now my first view is Login/password in table view controller.
As soon as the user hits done, i want my app to compare the login and password text fields with the Entity Login (with attributes : userid and password) and then display another view with the informations associated with that user (1 to 1) relationship.
Can any one help me with how to validate the login password and then display only the information associated with that user?
Any help would be really appreciated. I am totally new to this.
You need to create a Fetch request against that Entity (you will need to modify this to fit your specific needs:
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entity" inManagedObjectContext:context];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"username==%# AND password==%#",self.UsernameTextField.Text, self.PasswordTextField.Text];
[request setEntity:entity];
[request setPredicate:predicate];
... Do whatever you need to with the result (NSArray)
//first view controller
#import "ViewController.h"
#import "SecondViewController.h"
#import "SecondTableViewCell.h"
#import "AppDelegate.h"
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
#property(strong)NSMutableArray *company;
#end
#implementation ViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (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.
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"CompanyDetails"];
self.company = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableview reloadData];
}
#pragma mark-datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.company.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"sri";
SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.company
objectAtIndex:indexPath.row];
cell.lbl_c.text=[NSString stringWithFormat:#"%#", [device valueForKey:#"companyName"]];
cell.lbl_e .text=[NSString stringWithFormat:#"%#" , [device valueForKey:#"empName"]];
cell.lbl_s .text=[NSString stringWithFormat:#"%#", [device valueForKey:#"salary"]];
cell.img_g.image =[UIImage imageWithData:[device valueForKey:#"companyImage"]];
return cell;
}
// delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.company
objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.company removeObjectAtIndex:indexPath.row];
[self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"]) {
NSManagedObject *selectedDevice = [self.company objectAtIndex:[[self.tableview indexPathForSelectedRow] row]];
SecondViewController *vc2 = segue.destinationViewController;
vc2.device = selectedDevice;
}
}
#end
//second view controller
#import "SecondViewController.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface SecondViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
#end
#implementation SecondViewController
#synthesize device;
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
if (self.device) {
[self.txt_c setText:[self.device valueForKey:#"companyName"]];
[self.txt_e setText:[self.device valueForKey:#"empName"]];
[self.txt_s setText:[self.device valueForKey:#"salary"]];
self.img.image = [UIImage imageWithData:[self.device valueForKey:#"companyImage"]];
// self.txt_stdname.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentName"]];
//
// self.txt_strrollno.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentRollno"]];
//
// self.txt_stddept.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentDepartment"]];
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)btt_save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if(self.device)
{
[device setValue:self.txt_c.text forKey:#"companyName"];
[device setValue:self.txt_e.text forKey:#"empName"];
[device setValue:self.txt_s.text forKey:#"salary"];
NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0);
[device setValue:imgdata forKey:#"companyImage"];
}
else
{
NSManagedObject *comdetails = [NSEntityDescription insertNewObjectForEntityForName:#"CompanyDetails" inManagedObjectContext:context];
[comdetails setValue:self.txt_c.text forKey:#"companyName"];
[comdetails setValue:self.txt_e.text forKey:#"empName"];
[comdetails setValue:self.txt_s.text forKey:#"salary"];
NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0);
[comdetails setValue:imgdata forKey:#"companyImage"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# ", error.localizedDescription);
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btt_gallery:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
self.img.image = image;
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)btt_cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
// First view controller
#import "ViewController.h"
#import "ViewController6578.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface ViewController ()<UITextFieldDelegate>
{
NSArray *user;
}
- (IBAction)btt_reg:(id)sender;
#end
#implementation ViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (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.
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// AppDelegate *appDelegate =
// [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LogIn" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"userName==%#",self.txt_user.text];
[request setPredicate:predicate];
NSManagedObject *manage = nil;
NSError *error;
user=[managedObjectContext executeFetchRequest:request error:&error];
if([user count]==0)
{
NSLog(#"user and password");
}
else
{
manage =user[0];
_txt_pass.text = [manage valueForKey:#"password"];
}
}
- (IBAction)btt_log:(id)sender {
if((_txt_user.text.length == 0) || (_txt_pass.text.length==0))
{
NSLog(#"enter username and password");
}
else{
NSLog(#"%#,Login successfull",_txt_user.text);
}
}
- (IBAction)btt_reg:(id)sender {
ViewController6578 *vc2 = [self.storyboard instantiateViewControllerWithIdentifier:#"ndot"];
[self.navigationController pushViewController:vc2 animated:YES];
}
#end
//second view controller
#import "ViewController6578.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface ViewController6578 ()<UITextFieldDelegate>
#end
#implementation ViewController6578
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark-delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField becomeFirstResponder];
if(textField == _txt_user)
{
[_txt_pass becomeFirstResponder];
}
else if(textField == _txt_pass)
{
[_txt_email becomeFirstResponder];
}
else if(textField == _txt_email)
{
[_txt_email becomeFirstResponder];
}
else
{
[_txt_email resignFirstResponder];
}
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == _txt_user)
{
NSString *user =[_txt_user.text stringByReplacingCharactersInRange:range withString:string];
NSString *userRegex = #"^[A-Z0-9a-z]{6,10}$";
NSPredicate *userTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", userRegex];
if ([userTest evaluateWithObject:user] == YES)
{
_lbl1.text =#"";
}
else{
_lbl1.text =#"not valid";
}
}
if(textField ==_txt_pass)
{
NSString *pass =[_txt_pass.text stringByReplacingCharactersInRange:range withString:string];
NSString *passRegex =#"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,16}$";
NSPredicate *passTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",passRegex];
if ([passTest evaluateWithObject:pass] == YES)
{
_lbl2.text =#"";
}
else{
_lbl2.text =#"not valid";
}
}
if(textField ==_txt_email)
{
NSString *email =[_txt_email.text stringByReplacingCharactersInRange:range withString:string];
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if ([emailTest evaluateWithObject:email] == YES)
{
_lbl3.text =#"";
}
else{
_lbl3.text =#"not valid";
}
}
return YES;
}
- (IBAction)btt_save:(id)sender
{
if((_txt_user.text.length==0) || (_txt_pass.text.length==0) || (_txt_email.text.length==0))
{
UIAlertController *alert =[UIAlertController alertControllerWithTitle:#"title" message:#"please enter user,password,email" preferredStyle:UIAlertViewStyleDefault];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Yes, please"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
UIAlertAction* cancelButton = [UIAlertAction
actionWithTitle:#"No, thanks"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:yesButton];
[alert addAction:cancelButton];
[self presentViewController:alert animated:yesButton completion:nil];
}
else
{
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *details = [NSEntityDescription insertNewObjectForEntityForName:#"LogIn" inManagedObjectContext:context];
[details setValue:self.txt_user.text forKey:#"userName"];
[details setValue:self.txt_pass.text forKey:#"password"];
[details setValue:self.txt_email.text forKey:#"emailAddress"];
NSLog(#"12334%#",details);
NSError *error = nil;
_txt_user.text =#"";
_txt_pass.text =#"";
_txt_email.text =#"";
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# ",error .localizedDescription);
}
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btt_cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
#import "ViewController.h"
#import "secondTableViewCell.h"
#import "SecondViewController.h"
#interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UITableViewDelegate,UITableViewDataSource>
#property(nonatomic,strong)NSData *get_data;
#property(nonatomic,strong)NSMutableArray *result_array;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *base_url = #"https://itunes.apple.com/lookup?id=909253&entity=album";
NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:#"%#",base_url]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- nsurlconnection delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
{
NSLog(#"%#",error.localizedDescription);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
NSLog(#"%#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
NSLog(#"88888%#",data);
if ([data length])
{
self.get_data = [[NSData alloc]init];
self.get_data =data;
NSLog(#"%#",self.get_data);
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.get_data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"vijay%#",dict);
if (!error)
{
NSArray *array = [dict valueForKey:#"results"];
NSLog(#"1212%#",array);
self.result_array = [[NSMutableArray alloc]init];
self.result_array = [NSMutableArray arrayWithArray:array];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableview reloadData];
});
}
}
#pragma mark -uitableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.result_array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
secondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"sri"];
if (cell == nil)
{
cell = [[secondTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
cell.lbl1.text = [[self.result_array valueForKey:#"wrapperType"]objectAtIndex:indexPath.row];
cell.lbl2.text = [[self.result_array valueForKey:#"artistName"]objectAtIndex:indexPath.row];
cell.lbl3.text = [[self.result_array valueForKey:#"primaryGenreName"]objectAtIndex:indexPath.row];
// integer to string
NSInteger artid = [[[self.result_array valueForKey:#"artistId"]objectAtIndex:indexPath.row] integerValue];
NSString *str = [NSString stringWithFormat:#"%ld",(long)artid];
// NSInteger release = [[[self.result_array valueForKey:#"releaseDate"]objectAtIndex:indexPath.row] integerValue];
//
// NSString *str1 = [NSString stringWithFormat:#"%ld",(long)release];
//
// cell.lbl3.text = str;
//// // // float to string
// float a = [[[self.result_array valueForKey:#"collectionPrice"]objectAtIndex:indexPath.row]floatValue];
// NSString *str1 = [NSString stringWithFormat:#"%.2f",a];
//
cell.lbl4.text = str;
////
//
cell.img1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[_result_array valueForKey:#"artworkUrl60"]objectAtIndex:indexPath.row]]]]];
//
//
//
//
//
//
return cell;
}
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"segue" sender:self];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"]) {
//Do something
NSIndexPath *index = [self.tableview indexPathForSelectedRow];
SecondViewController *detailController = [segue destinationViewController];
// detailController.txt2= [cricket objectAtIndex:index.row];
detailController.imgg1= [UIImage imageNamed:[_result_array objectAtIndex:index.row]];
}
}
#end
#import "ViewController.h"
#import "CollectionViewCell1234.h"
#import "ViewController6778.h"
#interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate>
#property (nonatomic ,strong)NSData *resultdata;
#property ( nonatomic,strong)NSMutableArray *array1;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self webserviceCallingUsingGETMethod];
_collectionview.backgroundColor = [UIColor purpleColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- delegate
-(void)webserviceCallingUsingGETMethod
{
NSString *stringurl = #"https://itunes.apple.com/search?";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",stringurl]];
NSString *params = #"term=jack+johnson&entity=musicVideo";
NSData *postdata = [params dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postdata];
[NSURLConnection connectionWithRequest:request delegate:self];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(#"Error :%#", connectionError.localizedDescription);
return;
}
if (data) {
self.resultdata = data;
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_resultdata options:NSJSONReadingAllowFragments error:&error];
NSLog(#"RESULT :%#", result);
NSArray *array = [result valueForKey:#"results"];
_array1 =[[NSMutableArray alloc]init];
_array1 = [NSMutableArray arrayWithArray:array];
NSLog(#"122345%#",array);
dispatch_async(dispatch_get_main_queue(), ^{
[_collectionview reloadData];
});
}
}];
}
#pragma mark-collectionview delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _array1.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *nschool = #"sri";
CollectionViewCell1234 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:nschool forIndexPath:indexPath];
cell.imgview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[_array1 valueForKey:#"artworkUrl30"]objectAtIndex:indexPath.row]]]]];
cell.backgroundColor = [UIColor greenColor];
cell.lbl1.text = [[self.array1 valueForKey:#"wrapperType"]objectAtIndex:indexPath.row];
cell.lbl2.text = [[self.array1 valueForKey:#"artistName"]objectAtIndex:indexPath.row];
cell.lbl3.text = [[self.array1 valueForKey:#"releaseDate"]objectAtIndex:indexPath.row];
cell.lbl4.text = [[self.array1 valueForKey:#"country"]objectAtIndex:indexPath.row];
cell.lbl5.text = [[self.array1 valueForKey:#"currency"]objectAtIndex:indexPath.row];
cell.lbl6.text = [[self.array1 valueForKey:#"trackName"]objectAtIndex:indexPath.row];
cell.lbl7.text = [[self.array1 valueForKey:#"kind"]objectAtIndex:indexPath.row];
NSInteger artid= [[[self.array1 valueForKey:#"artistId"]objectAtIndex:indexPath.row]integerValue];
NSString *str1 =[NSString stringWithFormat:#"%ld",(long)artid];
cell.lbl8.text = str1;
CGFloat cp = [[[self.array1 valueForKey:#"collectionPrice"]objectAtIndex:indexPath.row]floatValue];
NSString *str4 = [NSString stringWithFormat:#"%3f",cp];
cell.lbl9.text = str4;
cell.lbl10.text = [[self.array1 valueForKey:#"collectionExplicitness"]objectAtIndex:indexPath.row];
cell.lbl11.text = [[self.array1 valueForKey:#"primaryGenreName"]objectAtIndex:indexPath.row];
NSInteger tracknum = [[[self.array1 valueForKey:#"trackId"]objectAtIndex:indexPath.row]integerValue];
NSString *str3 = [NSString stringWithFormat:#"%ld",(long)tracknum];
cell.lbl12.text = str3;
cell.lbl13.text = [[self.array1 valueForKey:#"trackExplicitness"]objectAtIndex:indexPath.row];
NSInteger tracknum1 =[[[self.array1 valueForKey:#"trackTimeMillis"]objectAtIndex:indexPath.row]integerValue];
NSString *str2 = [NSString stringWithFormat:#"%ld",(long)tracknum1];
cell.lbl14.text =str2;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"segue" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"])
{
ViewController6778 *vc2 = [segue destinationViewController];
vc2.img1.images ;
}
}
#end

Able to touch the background of activity indicator

In my iphone application an activity indicator is shown at the time of webservice call. My problem is that i am able to touch the view on which the activity indicator is shown.My view has textfields and buttons and i am able to enter values in the text fields and also change the button states while the activity indicator is still on it. Have anybody faced a similar situation? Does anybody know a solution to this problem? All helpful suggestions are welcomed.
Here is my activity indicator class.
ActivityProgressViewController.h
#import <UIKit/UIKit.h>
#interface ActivityProgressViewController : UIViewController {
IBOutlet UIActivityIndicatorView *_activityIndicator;
IBOutlet UILabel *_labelMessage;
NSString *_messageToShow;
}
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *activityIndicator;
#property (nonatomic, retain) IBOutlet UILabel *labelMessage;
+ (ActivityProgressViewController*) createInstance;
- (void)show;
- (void)showWithMessage:(NSString*)message;
- (void)close;
+ (void)show;
+ (void)close;
#end
ActivityProgressViewController.m
#import "ActivityProgressViewController.h"
#define kACTIVITY_INDICATOR_NIB #"ActivityProgressViewController"
#implementation ActivityProgressViewController
#synthesize activityIndicator = _activityIndicator;
#synthesize labelMessage = _labelMessage;
static ActivityProgressViewController *_viewController;
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad {
if (_messageToShow) _labelMessage.text = _messageToShow;
}
- (void)dealloc {
[_labelMessage release];
[_messageToShow release];
[_activityIndicator release];
[super dealloc];
}
+ (ActivityProgressViewController*) createInstance {
_viewController = [[ActivityProgressViewController alloc] initWithNibName:kACTIVITY_INDICATOR_NIB bundle:nil];
return _viewController;
}
- (void)show
{
[_activityIndicator startAnimating];
UIWindow *window = [[[UIApplication sharedApplication] windows]objectAtIndex:0];
NSLog(#"[[UIApplication sharedApplication] windows]===%#",[[UIApplication sharedApplication] windows]);
self.view.frame = CGRectMake(window.bounds.origin.x, window.bounds.origin.y, window.bounds.size.width, window.bounds.size.height);
[window addSubview:self.view];
}
- (void)showWithMessage:(NSString*)message {
_messageToShow = message;
[self show];
}
- (void)close
{
[self.view removeFromSuperview];
}
+ (void)show {
if (!_viewController) {
_viewController = [ActivityProgressViewController createInstance];
}
[_viewController show];
}
+ (void)close {
if (_viewController) {
[_viewController close];
}
}
#end
Here is how i call from my required class.
[ActivityProgressViewController show];
[ActivityProgressViewController close];
I also call the activity indicator while exporting audio.
This is the code I use for exporting
-(void)exportAudioFile:(AVComposition*)combinedComposition
{
[ActivityProgressViewController show];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:combinedComposition
presetName:AVAssetExportPresetPassthrough];
NSArray *presets =[AVAssetExportSession exportPresetsCompatibleWithAsset:combinedComposition];
NSLog(#"presets======%#",presets);
NSLog (#"can export: %#", exportSession.supportedFileTypes);
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
exportPath = [documentsDirectoryPath stringByAppendingPathComponent:#"CombinedNew.m4a"];
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = #"com.apple.m4a-audio";
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSLog (#"i is in your block, exportin. status is %d",
exportSession.status);
switch (exportSession.status)
{
case AVAssetExportSessionStatusFailed:
{
break;
}
case AVAssetExportSessionStatusCompleted:
{
exportSuccess = YES;
if (recorderFilePath)
{
NSError *finalurlError;
[[NSFileManager defaultManager]removeItemAtPath:recorderFilePath error:&finalurlError];
finalurlError = nil;
[[NSFileManager defaultManager]copyItemAtPath:[exportURL path] toPath:recorderFilePath error:&finalurlError];
NSLog(#"finalurlError 2-----%#",finalurlError);
}
[ActivityProgressViewController close];
fileUrl = [NSURL fileURLWithPath:recorderFilePath];
[self updatePlayerForUrl:fileUrl];
break;
}
case AVAssetExportSessionStatusUnknown:
{
break;
}
case AVAssetExportSessionStatusExporting:
{
break;
}
case AVAssetExportSessionStatusCancelled:
{
break;
}
case AVAssetExportSessionStatusWaiting:
{
break;
}
default:
{
NSLog (#"didn't get export status");
break;
}
};
}];
[exportSession release];
}
You're adding your activity indicator to the middle of another view, yes?
If so, you can do this in your show method:
self.superview.userInteractionEnabled = NO;
And in your close method:
self.superview.userInteractionEnabled = YES;
Here is where you'll find information on the UIView's userInteractionEnabled property: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instp/UIView/userInteractionEnabled
Hope this helps!