I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(#"Cancelled");
} else
{
NSLog(#"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
Thanks in advance.
Import the Social Framework:
#import <Social/Social.h>
-
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(#"Cancelled");
} else
{
NSLog(#"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:#"Test Post from mobile.safilsunny.com"];
[controller addURL:[NSURL URLWithString:#"http://www.mobile.safilsunny.com"]];
[controller addImage:[UIImage imageNamed:#"fb.png"]];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(#"UnAvailable");
}
}
/
//Deprecated in iOS6
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *account = [[ACAccount alloc] initWithAccountType:accountType];
NSLog(#"%#, %#", account.username, account.description);
}];
Here I got the answer, for posting image data and url together we need to add Social.framework, this framework is available in iOS6.
Just add the Social.framework in your project and add the blew code.
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(#"ResultCancelled");
} else
{
NSLog(#"Success");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller addURL:[NSURL URLWithString:#"https://itunes.apple.com/us/app/social-checkin/id504791401?mt=8"]];
if (encoded_ImageData == nil) {
[controller addImage:[UIImage imageNamed:#"No_ImageFound.png"]];
}
else
{
[controller addImage:[UIImage imageWithData:encoded_ImageData]];
}
NSString *businessName;
//Set business name string to be passed on facebook
if (m_BusinessNameString == nil || [m_BusinessNameString isEqualToString:#""])
{
businessName = #"Business name not specified!";
}
else
{
businessName = [m_BusinessNameString uppercaseString];
}
NSString *nameString = [NSString stringWithFormat:#"CHECKED IN #"];
//user has checked in with his friends if sc-merchant
NSString *friendsString;
if ([checkedFriendsNameArray count] > 0)
{
NSMutableString *checkedFriendsTempStr = [[NSMutableString alloc] init];
for (NSMutableString *checkedStr in checkedFriendsNameArray)
{
[checkedFriendsTempStr appendFormat:[NSString stringWithFormat:#"%#,",checkedStr]];
friendsString = [NSString stringWithFormat:#"WITH %#",checkedFriendsTempStr];
}
}
else
{
friendsString = [NSString stringWithFormat:#"WITH NO FRIENDS"];
}
NSString *fname= [[NSUserDefaults standardUserDefaults] valueForKey:#"userfname"];
NSString *lname= [[NSUserDefaults standardUserDefaults] valueForKey:#"userlname"];
NSString *name=[fname stringByAppendingString:[NSString stringWithFormat:#"%#",lname]];
NSString *main_TextString =[NSString stringWithFormat:#"%# \n %# %# %# %#",upperCaseStatusString,name,nameString,businessName,friendsString];
[controller setInitialText:main_TextString];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(#"UnAvailable");
}
Add below Code in your ViewController and import below framework.
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
#IBAction func btnPostClick(_ sender: Any)
{
if (FBSDKAccessToken.current() != nil)
{
if FBSDKAccessToken.current().hasGranted("publish_actions"){
postOnFB()
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
else{
print(error?.localizedDescription ?? "")
}
})
}
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
})
}
}
func postOnFB()
{
FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "YOUR MESSAGE"], httpMethod: "POST").start { (connection, result, error) in
if error == nil{
print("post id \(result ?? "")")
}
else{
print("error is \(error?.localizedDescription ?? "")")
}
}
}
this is possible in facebook-ios-sdk 3.0.
here
i am making the share with this code.
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
NSDictionary * result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
}
}];
i called this method when user clicks share button and there is no dialog with the user it directly post to the users wall. params is parameters that sharing includes.
Related
When I press 'Cancel' on a TouchID prompt, the prompt disappears and the instantly reappears... My biometrics method is called inside ViewDidLoad, I added an NSLog inside ViewDidLoad and it is getting called when I dismiss the TouchID dialog. I've looked and tried several examples of how to implement TouchID, but all result in the same outcome.
- (void)useBiometrics{
LAContext* context = [[LAContext alloc] init];
NSError* error = nil;
NSString* result = #"Use Touch ID to login";
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *storyboard=[UIStoryboard storyboardWithName:#"Main" bundle:[NSBundle mainBundle]];
LoginViewController *loginController = [storyboard instantiateViewControllerWithIdentifier:#"ViewControllerROOTIdentifier"];
[self.navigationController pushViewController:loginController animated:NO];
FROM_LOGIN = YES;
NEEDS_LOGIN = FALSE;
});
}
else
{
switch (error.code) {
case LAErrorSystemCancel:
{
break;
}
case LAErrorUserCancel:
{
NSLog(#"TouchID canceled");
break;
}
case LAErrorAuthenticationFailed:
{
break;
}
case LAErrorPasscodeNotSet:
{
break;
}
case LAErrorBiometryNotAvailable:
{
break;
}
case LAErrorBiometryNotEnrolled:
{
break;
}
case LAErrorUserFallback:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
break;
}
default:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
break;
}
}
}
}];
}
else
{
switch (error.code) {
case LAErrorBiometryNotEnrolled:
{
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(#"A passcode has not been set");
break;
}
default:
{
NSLog(#"TouchID not available");
break;
}
}
}
}
first time app install and share image is not working, it show alert:
This item cannot be shared. Please select a different item.
and I will try second time image share successfully. What is the issue?
-(void)TwitterAndmanyMore
{
UIImage * image = _imageView.image;
NSArray * items = #[image];
UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];
// and present it
[self presentActivityController:controller];
}
- (void)presentActivityController:(UIActivityViewController *)controller {
// for iPad: make the presentation a Popover
controller.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:controller animated:YES completion:nil];
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popController.barButtonItem = self.navigationItem.leftBarButtonItem;
// access the completion handler
controller.completionWithItemsHandler = ^(NSString *activityType,
BOOL completed,
NSArray *returnedItems,
NSError *error)
{
// react to the completion
NSLog(#"----retu------%#",returnedItems);
if (completed)
{
[self showContine];
//[self viewWillAppear:YES];
// user shared an item
NSLog(#"We used activity type%#", activityType);
} else {
// user cancelled
NSLog(#"We didn't want to share anything after all.");
}
if (error) {
NSLog(#"An Error occured: %#, %#", error.localizedDescription, error.localizedFailureReason);
}
};
}
use below code for this issue it work
-(void)TwitterAndmanyMore
{
// UIImage * image = _imageView.image;
// NSLog(#"Image Data %#",image);
// NSArray * items = #[#"", image];
tempImage = [UIImage imageNamed:#"Sample.jpg"];
tempImage = _imageView.image;
NSString *theMessage = #"";
NSArray *items;
CGImageRef cgref = [tempImage CGImage];
CIImage *cim = [tempImage CIImage];
if (cim != nil || cgref != NULL)
{
items = #[theMessage,tempImage];
}
else
{
items = #[theMessage];
}
NSLog(#"Image Data %#",items);
// build an activity view controller
UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];
// and present it
[self presentActivityController:controller];
}
- (void)presentActivityController:(UIActivityViewController *)controller {
// for iPad: make the presentation a Popover
controller.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:controller animated:YES completion:nil];
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popController.barButtonItem = self.navigationItem.leftBarButtonItem;
// access the completion handler
controller.completionWithItemsHandler = ^(NSString *activityType,
BOOL completed,
NSArray *returnedItems,
NSError *error)
{
// react to the completion
NSLog(#"----retu------%#",returnedItems);
if (completed)
{
[self showContine];
//[self viewWillAppear:YES];
// user shared an item
NSLog(#"We used activity type%#", activityType);
} else {
// user cancelled
NSLog(#"We didn't want to share anything after all.");
}
if (error) {
NSLog(#"An Error occured: %#, %#", error.localizedDescription, error.localizedFailureReason);
}
};
}
I try to create an application that records video and takes images at receiving a message via sockets.
What I do not arrive to do is video recording using AVFoundation.
is that because of the fact that I use a single session ?
Here is my code :
#import "ViewController.h"
#import "Parser.h"
#import "DeviceConfig.h"
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// z-index
_vImage.layer.zPosition = 1;
_toggle.layer.zPosition = 1;
recording = NO;
[self initNetworkCommunication];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"192.168.0.103", 8080, &readStream, &writeStream);
input = (__bridge NSInputStream*) readStream;
output = (__bridge NSOutputStream*) writeStream;
[input setDelegate: self];
[output setDelegate: self];
[input scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[output scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[input open];
[output open];
}
- (void) sendMessage : (NSString*) message {
NSString *response = [NSString stringWithFormat:#"iam:%#", message];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[output write:[data bytes] maxLength:[data length]];
}
- (void) stream : (NSStream*) theStream handleEvent:(NSStreamEvent) streamEvent {
switch(streamEvent) {
case NSStreamEventOpenCompleted:
[self openCamera];
break;
case NSStreamEventHasBytesAvailable:
NSLog(#"kayn");
if(theStream == input) {
uint8_t buffer[1024];
int length;
while([input hasBytesAvailable]) {
length = [input read:buffer maxLength:sizeof(buffer)];
if(length > 0) {
NSString* outputString = [[NSString alloc] initWithBytes:buffer length:length encoding:NSASCIIStringEncoding];
// To split different messages sended in buffer via Socket (in one message)
NSArray *options = [[outputString substringToIndex:[outputString length] - 1] componentsSeparatedByString:#":"];
NSLog(#"%#", options);
if(outputString != nil) {
if([options[1] isEqualToString:#"TAKE_PIC"]) {
[self takePic];
}else if([options[1] isEqualToString:#"PARAMS"]) {
Parser* parser = [[Parser alloc] initWithXMLData: options[2]];
[self changeCameraConfig:[parser getCameraOptions]];
}else if([options[1] isEqualToString:#"REC_VIDEO"]) {
[self recordVideo];
}else{
[self showMessage:#"Unknow order, please contact the administrator."];
}
}
}
}
}
break;
default:
NSLog(#"Unknown event");
}
}
- (void) showMessage : (NSString*) msg {
UIAlertView *helloWorldAlert = [[UIAlertView alloc]
initWithTitle:#"My First App" message:msg delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[helloWorldAlert show];
}
- (void) openCamera {
session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetHigh;
AVCaptureVideoPreviewLayer* previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
previewLayer.frame = self.liveCameraView.bounds;
[self.liveCameraView.layer addSublayer:previewLayer];
device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
[session addInput:deviceInput];
_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[_stillImageOutput setOutputSettings:outputSettings];
_videoOutput = [[AVCaptureMovieFileOutput alloc] init];
[session addOutput:_videoOutput];
[session addOutput:_stillImageOutput];
[session startRunning];
}
-(void) changeCameraConfig:(NSMutableDictionary *)config {
[device lockForConfiguration:nil];
DeviceConfig* conf;
for(id key in config) {
conf = [config objectForKey:key];
//[self showMessage:#"ok"];
// Config Torch
if([key isEqualToString:#"torch"]) {
if([[conf curValue] isEqualToString: #"on"]) {
[device setTorchMode:AVCaptureTorchModeOn];
}else{
[device setTorchMode:AVCaptureTorchModeOff];
}
}
// Config Focus
if([key isEqualToString:#"focus_mode"]) {
if([[conf curValue] isEqualToString: #"auto"]) {
[device setFocusMode: AVCaptureFocusModeAutoFocus];
}else if([[conf curValue] isEqualToString: #"continous_auto"]) {
[device setFocusMode: AVCaptureFocusModeContinuousAutoFocus];
}else{
[device setFocusMode: AVCaptureFocusModeLocked];
}
}
// Config Flash
if([key isEqualToString:#"flash"]) {
if([[conf curValue] isEqualToString: #"on"]) {
[device setFlashMode: AVCaptureFlashModeOn];
}else{
[device setFlashMode:AVCaptureFlashModeOff];
}
}
// Config Exposure
if([key isEqualToString:#"white_balance"]) {
if([[conf curValue] isEqualToString: #"auto"]) {
[device setExposureMode: AVCaptureExposureModeAutoExpose];
}else if([[conf curValue] isEqualToString: #"continous_auto"]) {
[device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}else if([[conf curValue] isEqualToString: #"custom"]) {
[device setExposureMode:AVCaptureExposureModeCustom];
}else{
[device setExposureMode:AVCaptureExposureModeLocked];
}
}
// Config White balance
if([key isEqualToString:#"exposure_mode"]) {
if([[conf curValue] isEqualToString: #"auto"]) {
[device setExposureMode: AVCaptureExposureModeAutoExpose];
}else if([[conf curValue] isEqualToString: #"continous_auto"]) {
[device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}else if([[conf curValue] isEqualToString: #"custom"]) {
[device setExposureMode:AVCaptureExposureModeCustom];
}else{
[device setExposureMode:AVCaptureExposureModeLocked];
}
}
}
[device unlockForConfiguration];
}
-(void) takePic {
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
NSLog(#"about to request a capture from: %#", _stillImageOutput);
[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
if (exifAttachments)
{
// Do something with the attachments.
NSLog(#"attachements: %#", exifAttachments);
}
else
NSLog(#"no attachments");
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
self.vImage.image = image;
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}];
}
- (AVCaptureDevice *) CameraWithPosition:(AVCaptureDevicePosition) Position
{
NSArray *Devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *Device in Devices)
{
if ([Device position] == Position)
{
return Device;
}
}
return nil;
}
/*
#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)toggleCam:(id)sender {
AVCaptureDeviceInput* newDeviceInput;
NSError* error;
AVCaptureDevicePosition position = [[deviceInput device] position];
if(position == AVCaptureDevicePositionBack) {
newDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self CameraWithPosition:AVCaptureDevicePositionBack] error:&error];
}else{
newDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self CameraWithPosition:AVCaptureDevicePositionFront] error:&error];
}
if(error != nil) {
[session beginConfiguration]; //We can now change the inputs and output configuration. Use commitConfiguration to end
[session removeInput:deviceInput];
if ([session canAddInput:newDeviceInput])
{
[session addInput:newDeviceInput];
deviceInput = newDeviceInput;
}
else
{
[session addInput:deviceInput];
}
//Set the connection properties again
//[self CameraSetOutputProperties];
[session commitConfiguration];
}
}
-(void) recordVideo {
[self showMessage:#"recording .."];
// If we are not recording
if(!recording) {
recording = YES;
NSString* path = [[NSString alloc] initWithFormat:#"%#%#", NSTemporaryDirectory(), #"output_video.wav"];
NSURL* url = [[NSURL alloc] initFileURLWithPath:path];
NSFileManager* fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:path]) {
NSError* errorMsg;
if ([fileManager removeItemAtPath:path error:&errorMsg] == NO)
{
//Error - handle if requried
}
}
[_videoOutput startRecordingToOutputFileURL:url recordingDelegate:self];
}else{
recording = NO;
[_videoOutput stopRecording];
}
}
-(void) captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
BOOL recordedSuccessfully = YES;
if ([error code] != noErr) {
// A problem occurred: Find out if the recording was successful.
id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
if (value) {
recordedSuccessfully = [value boolValue];
}
}
if(recordedSuccessfully) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if([ALAssetsLibrary authorizationStatus]) {
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputFileURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
}
}];
}
}else{
[self showMessage:#"Error"];
}
}
}
#end
I am making a game in which the player can achieve a positive high score or a negative low score depending on the choices they make. The high score has been working fine, but I'm having trouble with the low score.
-(void)authenticateLocalPlayer{
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
if (viewController != nil) {
[self presentViewController:viewController animated:YES completion:nil];
}
else{
if ([GKLocalPlayer localPlayer].authenticated) {
_gameCenterEnabled = YES;
// Get the default leaderboard identifier.
[[GKLocalPlayer localPlayer] loadDefaultLeaderboardIdentifierWithCompletionHandler:^(NSString *leaderboardIdentifier, NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
else{
_leaderboardIdentifier = leaderboardIdentifier;
}
}];
}
else{
_gameCenterEnabled = NO;
}
}
};
}
-(void)reportScore{
GKScore *highscore = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
highscore.value = HighScoreNumber;
[GKScore reportScores:#[highscore] withCompletionHandler:^(NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}];
-(void)showLeaderboardAndAchievements:(BOOL)shouldShowLeaderboard{
GKGameCenterViewController *gcViewController = [[GKGameCenterViewController alloc] init];
gcViewController.gameCenterDelegate = self;
if (shouldShowLeaderboard) {
gcViewController.viewState = GKGameCenterViewControllerStateLeaderboards;
gcViewController.leaderboardIdentifier = _leaderboardIdentifier;
}
else{
gcViewController.viewState = GKGameCenterViewControllerStateAchievements;
}
[self presentViewController:gcViewController animated:YES completion:nil];
}
You'll notice leaderboardidentifier, it is useful for reporting scores to the default leaderboard, but when I try to get it to work for two different ones, the code shuts down.
I've tried adding this to "Report Score":
GKScore *lowscore = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
lowscore.value = LowScoreNumber;
[GKScore reportScores:#[lowscore] withCompletionHandler:^(NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}];
}
Then, I change the leaderboard identifiers to match itunesconnect, but I'm not sure how I need to change authenticateLocalPlayer and shouldShowLeaderboardandAchievements.
I have some experience with game center. I have two games on the App Store that have multiple leaderboards (Squared!! and Primes!).
Instead of having one method for each leaderboard I made one method for submitting scores. Here is that method:
-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard
{
//1: Check if Game Center
// features are enabled
if (!_gameCenterFeaturesEnabled) {
return;
}
//2: Create a GKScore object
GKScore* gkScore =
[[GKScore alloc]
initWithLeaderboardIdentifier:leaderboard];
//3: Set the score value
gkScore.value = score;
//4: Send the score to Game Center
[gkScore reportScoreWithCompletionHandler:
^(NSError* error) {
[self setLastError:error];
BOOL success = (error == nil);
if ([_delegate
respondsToSelector:
#selector(onScoresSubmitted:)]) {
[_delegate onScoresSubmitted:success];
}
}];
}
When you want to submit your high scores all you have to do is add something like:
[[GCHelper sharedGameKitHelper] submitScore:myLowScore Leaderboard:TELS];
[[GCHelper sharedGameKitHelper] submitScore:myHighScore Leaderboard:TEHS];
GCHelper is the class that contains my submitScore:Leaderboard: method.
To view your leaderboards or achievements within your app try this:
- (void) presentLeaderboards {
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc] init];
gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
gameCenterController.gameCenterDelegate = self;
[self presentViewController:gameCenterController animated:YES completion:nil];
}
- (void) gameCenterViewControllerDidFinish:(GKGameCenterViewController*) gameCenterViewController {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void) presentAchievements {
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc] init];
gameCenterController.viewState = GKGameCenterViewControllerStateAchievements;
gameCenterController.gameCenterDelegate = self;
I hope this answers your question!
I have problem with the attached codе. It have to close the currently displayed modalViewController when the user tap once on the cancel button instead of twice as it do now.
Code
- (BOOL)isIOS6 {
BOOL native = YES;
if([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0f){
native = NO;
}
return native;
}
- (void)twitterShare {
DLog(#"is ios6: %d", [self isIOS6]);
if ([self isIOS6]) {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
NSString *textToShare = #"Test";
SLComposeViewController *twitterComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
twitterComposeViewController.completionHandler = ^(SLComposeViewControllerResult result){
DLog(#"result: %d", result);
if (result == 1) {
Dlog(#"Shared");
[[NSNotificationCenter defaultCenter] postNotificationName:#"notitificationName" object:nil];
DLog(#"Sended provide bonus notification");
[self disableButtonWithTag:GrowthButtonTwitterConnectTag];
DLog(#"disable that button.");
} else {
Dlog(#"canceled...");
}
};
[twitterComposeViewController setInitialText:textToShare];
[self presentViewController:twitterComposeViewController animated:YES completion:nil];
} else {
DLog(#"Twitter not available");
}
} else {
// iOS 5 not supported message
[[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"ATTENTION", nil)
message:NSLocalizedString(#"IOS6_OR_ABOVE_FEATURE", nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", nil)
otherButtonTitles:nil, nil] autorelease] show];
}
}
I've manage to fix that issue with the following code:
tweetSheet.completionHandler = ^(SLComposeViewControllerResult result) {
switch(result) {
// This means the user cancelled without sending the Tweet
case SLComposeViewControllerResultCancelled:
break;
// This means the user hit 'Send'
case SLComposeViewControllerResultDone:
[[NSNotificationCenter defaultCenter] postNotificationName:#"kGrowthProvideTwitterBonus" object:nil];
DLog(#"Sended provide bonus notification");
[self disableButtonWithTag:TTGrowthButtonTwitterConnectTag];
break;
}
// dismiss the Tweet Sheet
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:NO completion:^{
NSLog(#"Tweet Sheet has been dismissed.");
}];
});
};