I am getting the above error when using uiimagepicker controller. Here is my code:
- (BOOL) startCameraControllerFromViewController:(UIViewController *)controller andisImageFromCamera:(BOOL)isCameraCapture {
if(self.picker == nil) {
/**< instansiate UIImagePickerController object */
self.picker = [[UIImagePickerController alloc] init];;
}
/**< Check isSourceTypeAvailable for possible sources (camera and photolibrary) */
if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] == NO) || ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO))
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Oops!! This feature is not supported on your device" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
return NO;
}
self.picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
self.picker.delegate = self;
self.picker.mediaTypes =[NSArray arrayWithObjects: (NSString *) kUTTypeMovie, (NSString *) kUTTypeImage, nil];
self.picker.videoMaximumDuration = MAX_VIDEO_DURATION;
self.picker.allowsEditing = YES;
self.picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
/**< if editing is required*/
[self presentViewController:self.picker animated:YES completion:^{
}];
return YES;
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSURL *videoURL = [info valueForKey:UIImagePickerControllerMediaURL];
NSString *pathToVideo = [videoURL path];
if(![pathToVideo isEqualToString:#""] && pathToVideo != nil) {
BOOL okToSaveVideo = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(pathToVideo);
if (okToSaveVideo) {
//UISaveVideoAtPathToSavedPhotosAlbum(pathToVideo, self, #selector(video:didFinishSavingWithError:contextInfo:), NULL);
}
}
if ([info[UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]) {
// video
isVideoFromGallery = YES;
isMediaTypeVideo = YES;
[self videoCaptureSaveAction:videoURL andMediaInfo:info];
}
else{
isMediaTypeVideo = NO;
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.previewImage = chosenImage;
self.capturedImageData = UIImageJPEGRepresentation(chosenImage, 90);
[self performSegueWithIdentifier:#"previewCapture" sender:self];
}
}
Picking the video is working. But when i am selecting the image i am gettin the error: [Generic] Creating an image format with an unknown type is an error. I have read other posts about this error, changed the delegate method, but still its not working. Please help.
I have an iPhone game in Appstore, I recently tried to upload an updated build with latest Xcode but it was rejected because the inApp-purchases were not working on ipv6 only network. It's working fine with ipv4 network.
//
// ViewController.m
//
NSMutableArray * arrayOfSection;
NSMutableArray * sectionHeaders;
NSString *error;
#import "CoinsController.h"
#import "NSString+SBJSON.h"
#import <CommonCrypto/CommonDigest.h>
#implementation CoinsController
#synthesize bkg;
-(void) callPurchaseId:(NSString*)iapId amount:(NSUInteger)ncoins{
SKPayment *payment = [SKPayment paymentWithProductIdentifier:iapId];
//[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.9;
[UIView commitAnimations];
loadingtext.text = #"Processing Purchase";
NSLog(#"Processing Purhcase");
// currentGem = [NSString stringWithFormat:#"vegas%#", #"80k"];
[CommonUtilities encryptString:[NSString stringWithFormat:#"%lu", (unsigned long)ncoins]:#"c"];
NSLog(#"Processing");
}
- (IBAction)purchaseCoins:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(#"%li", (long)button.tag);
switch (button.tag) {
case 1001:
[self callPurchaseId:IAP1 amount:IAP_AMT_1];
break;
case 1002:
[self callPurchaseId:IAP2 amount:IAP_AMT_2];
break;
case 1003:
[self callPurchaseId:IAP3 amount:IAP_AMT_3];
break;
case 1004:
[self callPurchaseId:IAP4 amount:IAP_AMT_4];
break;
case 1005:
[self callPurchaseId:IAP5 amount:IAP_AMT_5];
break;
case 1006:
[self callPurchaseId:IAP6 amount:IAP_AMT_6];
break;
default:
break;
}
}
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
nf.usesGroupingSeparator = YES;
nf.groupingSize = 3;
((UILabel*)[self.view viewWithTag:2001]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_1]]];
((UILabel*)[self.view viewWithTag:2002]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_2]]];
((UILabel*)[self.view viewWithTag:2003]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_3]]];
((UILabel*)[self.view viewWithTag:2004]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_4]]];
((UILabel*)[self.view viewWithTag:2005]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_5]]];
((UILabel*)[self.view viewWithTag:2006]).text = [NSString stringWithFormat:#"%# Coins", [nf stringFromNumber:[NSNumber numberWithInteger:IAP_AMT_6]]];
[nf release];
}
- (void)requestProUpgradeProductData
{
NSLog(#"called productsRequest");
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.9;
[UIView commitAnimations];
loadingtext.text = #"Connecting to Store";
if([cost1000.text isEqual:#"0.00"]){
NSSet *productIdentifiers = [NSSet setWithObjects:IAP1, IAP2, IAP3, IAP4, IAP5, IAP6, nil];
SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
productsRequest.delegate = self;
[productsRequest start];
}else{
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
}
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSString *sym = #"";
NSArray *items = response.products;
for(SKProduct *itemproduct in items)
{
NSLog(#"Product title: %# - %#" , itemproduct.localizedTitle, itemproduct.priceAsString);
//NSLog(#"Product description: %#" , item.localizedDescription);
//NSLog(#"Product price: " , ;
NSLog(#"Product id: %#" , itemproduct.productIdentifier);
if([itemproduct.productIdentifier isEqual:IAP1]){
cost1000.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}else if([itemproduct.productIdentifier isEqual:IAP2]){
cost3200.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}else if([itemproduct.productIdentifier isEqual:IAP3]){
cost8000.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}else if([itemproduct.productIdentifier isEqual:IAP4]){
cost20000.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}else if([itemproduct.productIdentifier isEqual:IAP5]){
cost80000.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}else if([itemproduct.productIdentifier isEqual:IAP6]){
cost200000.text = [sym stringByAppendingString:[NSString stringWithFormat:#"%#", itemproduct.priceAsString]];
}
}
for (NSString *invalidProductId in response.invalidProductIdentifiers)
{
NSLog(#"Invalid product id: %#" , invalidProductId);
error = #"YES";
}
if([error isEqual:#"YES"]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Payments Error Occured" message:#"Could not read payment information from Apple In-App Servers. Please try again later" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[self dismissViewControllerAnimated:YES completion:nil];
error = #"NO";
}
// finally release the reqest we alloc/init’ed in requestProUpgradeProductData
//[productsRequest release];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
}
//
// removes the transaction from the queue and posts a notification with the transaction result
//
- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful
{
// remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
if (wasSuccessful)
{
#ifdef kURL_VERIFY_PURCHASE_RECEIPT
NSString *jsonObjectString = [CommonUtilities encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];
////NSLog(jsonObjectString);
[CommonUtilities encryptString:[CommonUtilities md5:jsonObjectString]:#"b"];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.9;
[UIView commitAnimations];
//loadingtext.text = #"Purchase Completing";
loadingtext.text = #"Completing Transaction";
NSString *httpBodyString=[[NSString alloc] initWithFormat:#"receipt=%#&userid=%#",jsonObjectString, [CommonUtilities decryptString:#"username"]];
NSString *urlString=kURL_VERIFY_PURCHASE_RECEIPT;
NSURL *url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
NSString *postLength = [NSString stringWithFormat:#"%d", [httpBodyString length]];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
responseData=[[NSMutableData data] retain];
#else
int addCoins = [[CommonUtilities decryptString:#"c"] intValue];
int currentCoins = [[CommonUtilities decryptString:#"coins"] intValue];
int newCoins = addCoins + currentCoins;
[CommonUtilities encryptString:[NSString stringWithFormat:#"%i", newCoins]:#"coins"];
// due to sync issues we add + 1 to xp so sync to server completes
NSLog(#"transaction complete");
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
#endif
}
else
{
NSLog(#"Purchase failed");
// send out a notification for the failed transaction
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, #"transaction" , nil];
//[[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerTransactionFailedNotification object:self userInfo:userInfo];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
}
}
//
// called when the transaction was successful
//
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
[self finishTransaction:transaction wasSuccessful:YES];
}
//
// called when a transaction has failed
//
- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
if (transaction.error.code != SKErrorPaymentCancelled)
{
// error!
[self finishTransaction:transaction wasSuccessful:NO];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
NSLog(#"error transaction");
}
else
{
// this is fine, the user just cancelled, so don’t notify
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
NSLog(#"cancelled transaction");
}
}
//
// called when the transaction status is updated
//
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
default:
break;
}
}
}
#pragma mark -
- (IBAction)closeCoins:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad
{
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
webView.opaque = NO;
webView.backgroundColor = [UIColor clearColor];
webView.dataDetectorTypes = UIDataDetectorTypeLink;
jackpotView.opaque = NO;
jackpotView.backgroundColor = [UIColor clearColor];
//[self didLoad];
NSString *filename = #"store.jpg";
CGRect screenRect = [[UIScreen mainScreen] bounds];
if (screenRect.size.width == 568.0f) {
filename = [filename stringByReplacingOccurrencesOfString:#".jpg" withString:#"-568h#2x.jpg"];
[self.bkg setBounds:CGRectMake(0, 0, screenRect.size.width, screenRect.size.height)];
NSLog(#"YAGO - changing background: %#", filename);
}
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
filename = #"store-ipad.jpg";
}
self.bkg.image = [UIImage imageNamed:filename];
viewLoading.alpha = 0.0;
viewNoInternet.alpha = 0.0;
// reachability
[self tryConnect:nil];
if([SKPaymentQueue canMakePayments]){
////NSLog(#"can make payments");
[self requestProUpgradeProductData];
}else{
////NSLog(#"cannot make payments");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Payments Disabled" message:#"In-App Purchases are disabled on this device." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[self dismissViewControllerAnimated: YES completion:nil];
}
CGSize result = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [UIScreen mainScreen].scale;
result = CGSizeMake(result.width * scale, result.height * scale);
if(result.height == 960){
bar.frame = CGRectMake(0,0,(result.height / 2),32);
}else if(result.height == 1136){
bar.frame = CGRectMake(0,0,(result.height / 2),32);
}else if(result.height == 1024){
bar.frame = CGRectMake(0,0,result.height,44);
}else if (result.height == 2048){
bar.frame = CGRectMake(0,0,result.height/2,44);
}
else{
bar.frame = CGRectMake(0,0,(result.height),32);
}
int fontSize = 16;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
//[[UILabel appearance] setFont:[UIFont fontWithName:#"Myriad Web Pro" size:28.0]];
}else{
//[[UILabel appearance] setFont:[UIFont fontWithName:#"Myriad Web Pro" size:12.0]];
fontSize = 12;
}
UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];
UIImage *buttonBack32 = [[UIImage imageNamed:#"NavigationBackButton"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 5)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:buttonBack32 forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],
UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
UITextAttributeTextShadowOffset,
[UIFont fontWithName:#"Helvetica-Bold" size:fontSize],
UITextAttributeFont,
nil]
forState:UIControlStateNormal];
self.navigationItem.backBarButtonItem = backButton;
}
-(void)viewWillDisappear:(BOOL)animated{
NSLog(#"coins has gone");
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateCoins" object:self];
[[NSNotificationCenter defaultCenter] postNotificationName:#"sortCoins" object:self];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
//[[UILabel appearance] setFont:[UIFont fontWithName:#"Myriad Web Pro" size:20.0]];
}else{
//[[UILabel appearance] setFont:[UIFont fontWithName:#"Myriad Web Pro" size:10.0]];
}
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscape;
}
- (BOOL) shouldAutorotate {
return YES;
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight){
return YES;
}else{
return NO;
}
}
- (void)dealloc {
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
[self.bkg release];
[super dealloc];
}
#pragma mark for server side validation (no customer support)
// these connection-related methods are only here to help in case you ever decide to implement
// server-side validation of purchase receipts
// - in this case, you'll also need to define your own kURL_VERIFY_PURCHASE_RECEIPT and figure out the existing validation protocol (I can't provide you with support on this one, it's code written by someone else)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
//NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
//NSDictionary *dictionary = [httpResponse allHeaderFields];
//NSLog([dictionary description]);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
//NSString *a = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"Data: %#", a);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Connection" message:#"You are not connected to the internet or data. Please connect and try again." delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//////NSLog(responseString);
NSString *gKey = [CommonUtilities decryptString:#"b"];
NSString *result = [CommonUtilities base64Decrypt:responseString:gKey];
NSLog(#"%#",result);
int r = [result intValue];
////NSLog(#"r int: %i", r);
if(r == 1){
int addCoins = [[CommonUtilities decryptString:#"c"] intValue];
int currentCoins = [[CommonUtilities decryptString:#"coins"] intValue];
int newCoins = addCoins + currentCoins;
[CommonUtilities encryptString:[NSString stringWithFormat:#"%i", newCoins]:#"coins"];
// due to sync issues we add + 1 to xp so sync to server completes
NSLog(#"transaction complete");
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Receipt Failed" message:#"Please make the purchase again using a vaild iTunes account" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
[self dismissViewControllerAnimated:YES completion:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(fadeOut:finished:context:)];
viewLoading.alpha = 0.0;
[UIView commitAnimations];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
#end
I don't know whats wrong with this code. The only thing I get in the xcode debug log is "Purchase failed" .
Any help will be highly appreciated.
Turns out the problem wasn't on my side . Since sandbox.itunes.apple.com does not have an ipv6 address so it works with DNS64 (or NAT64 or whatever this thing is :D .I don't know much about this stuff) and not on a real ipv6 only network.
Not sure why they rejected my app the first time but it was approved after I resubmitted it .
I am recieving an error on this line in my ViewControllerLogin.m file or anywhere a UIAlert shows up...
[UIAlertView error:#"Enter username and password over 4 chars each."];
The above code gives me an error in the issues editor: "no known class for method selector". I identified the method 'error' in another class in Xcode. Does anyone know why I am getting this error?
UPDATE ViewControllerLogin.m (the UIViewAlets are at the bottom)
#import "ViewControllerLogin.h"
#import "UIAlertView+error.h"
#import "API.h"
#include <CommonCrypto/CommonDigest.h>
#define kSalt #"adlfu3489tyh2jnkLIUGI&%EV(&0982cbgrykxjnk8855"
#implementation ViewControllerLogin
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:animated];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:animated];
[super viewWillDisappear:animated];
}
-(void)viewDidLoad {
[super viewDidLoad];
//focus on the username field / show keyboard
[fldUsername becomeFirstResponder];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"qwertygreen.png"] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.title = #"play";
//changes the buttn color
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
// Do any additional setup after loading the view.
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - View lifecycle
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(IBAction)btnLoginRegisterTapped:(UIButton*)sender {
//form fields validation
if (fldUsername.text.length < 4 || fldPassword.text.length < 4)
{
[UIAlertView error:#"Enter username and password over 4 chars each."];
return;
}
//salt the password
NSString* saltedPassword = [NSString stringWithFormat:#"%#%#", fldPassword.text, kSalt];
//prepare the hashed storage
NSString* hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
//hash the pass
NSData *data = [saltedPassword dataUsingEncoding: NSUTF8StringEncoding];
if (CC_SHA1([data bytes], [data length], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
} else {
[UIAlertView error:#"Password can't be sent"];
return;
}
//check whether it's a login or register
NSString* command = (sender.tag==1)?#"register":#"login";
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", fldUsername.text, #"username", hashedPassword, #"password", nil];
//make the call to the web API
[[API sharedInstance] commandWithParams:params onCompletion:^(NSDictionary *json) {
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
[[API sharedInstance] setUser: res];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//show message to the user
[[[UIAlertView alloc] initWithTitle:#"Logged in" message:[NSString stringWithFormat:#"Welcome %#",[res objectForKey:#"username"]] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil] show];
} else {
//error
[UIAlertView error:[json objectForKey:#"error"]];
}
}];
}
#end
You need to import UIKit.
#import <UIKit/UIKit.h>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
On cameraviewcontrolle.mr I take a picture or movie using UIImagePickerController. On completion, I call back to aanvraagviewcontroller.m.
I want to save the the picture by tapping on send button.
My question comes to this I think, how can I import .m file or take the picture/movie to aanvraagviewcontroller.m (I use Parse.com to save my PFObjects)?
This is cameraviewcontroller.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was taken/selected!
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
else {
// A video was taken/selected!
self.videoFilePath = (__bridge NSString *)([[info objectForKey:UIImagePickerControllerMediaURL] path]);
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the video!
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil);
}
}
}
[self uploadMessage];
[self dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popToRootViewControllerAnimated:YES];}
- (void)uploadMessage {
NSData *fileData;
NSString *fileName;
NSString *fileType;
if (self.image != nil) {
UIImage *newImage = [self resizeImage:self.image toWidth:320.0f andHeight:480.0f];
fileData = UIImagePNGRepresentation(newImage);
fileName = #"image.png";
fileType = #"image";
}
else {
fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
fileName = #"video.mov";
fileType = #"video";
}
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {// onderdeelAanvraag[#"file"] = file;
// onderdeelAanvraag[#"fileType"] = fileType;
// onderdeelAanvraag[#"recipientIDs"] = self.recipients;
//
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
// Everything was successful!
[self reset];
}
// }];
}
}];
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
[self.recipients removeAllObjects];
}
- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
CGSize newSize = CGSizeMake(width, height);
CGRect newRectangle = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(newSize);
[self.image drawInRect:newRectangle];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
This is aanvraagviewcontroller.m (when send button is pressed, i want to save the picture/movie here);
- (IBAction)verstuurAanvraag:(id)sender {
NSString *onderdeelOmschrijving = self.onderdeelOmschrijvingField.text ;
NSString *autoOmschrijving = self.autoOmschrijvingField.text ;
if ([onderdeelOmschrijving length] == 0 ||
[autoOmschrijving length] == 0)
{
UIAlertView *alertView = [[ UIAlertView alloc] initWithTitle:#"Leeg veld" message:#"Vul de lege velden in" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
else {
PFObject *onderdeelAanvraag = [PFObject objectWithClassName:#"Aanvragen"];
[onderdeelAanvraag setObject:[PFUser currentUser] forKey:#"Aanvrager"];
onderdeelAanvraag[#"OnderdeelOmschrijving"] = onderdeelOmschrijving;
onderdeelAanvraag[#"AutoOmschrijving"] = autoOmschrijving;
NSDate *date = [NSDate date];
onderdeelAanvraag[#"Datum"] =date;
onderdeelAanvraag[#"file"] = file;
onderdeelAanvraag[#"fileType"] = fileType;
onderdeelAanvraag[#"recipientIDs"] = self.recipients;
// Get random number between 0 and 999999
int nummer = arc4random() % 100000;
NSLog(#"nieuw nummer %d", nummer);
[onderdeelAanvraag setObject:[NSNumber numberWithInt:nummer] forKey:#"AanvraagNummer"];
[onderdeelAanvraag saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!" message: [error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
[self performSegueWithIdentifier:#"showRecipients" sender:self];
}
}];
}
}
I SOLVED PASSING UITEXTFIELD TEXT BY THIS ;
I solved passing textfield data passing with the segue method like here ;
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showRecipients"]){
OntvangersViewController *controller;
controller = [segue destinationViewController];
controller.onderdeelOmschrijvingField = self.onderdeelOmschrijvingField;
controller.autoOmschrijvingField = self.autoOmschrijvingField;
controller.image = self.image;
controller.videoFilePath = self.videoFilePath;
NSLog(#"videofilepath %#", self.videoFilePath);
controller.recipients = self.recipients;
}
}
Your question is muddled and confused.
The code in a .m file is not shared with other .m files.
The whole point of the C .h header file is that the header file can be shared, while the implementation (.c, or .m for Objective C) is private, and not shared.
If you want a value to be visible to another class, or another object of the same class, you should define a property in the header file.
If you want to pass a value from one view controller to another, this topic has been covered Ad nauseam here and on other forums. There are at least 2 comments on your post pointing you to other threads covering the topic.
I am trying to present a camera view controller with a custom overlay containing two labels. I have been unable to get my imagePickerControllerDidCancel method and alertView to work properly. The system is printing the correct information to the NSLog but the lines of code that I have written are not doing anything and when the user taps 'Back' (to cancel the alertView and return to the imagePicker) the camera appears again but the takePhoto button and Cancel button are no longer accessible. They can still be seen but not tapped. When the user clicks the button at index 1 (Leave) I want the camera to be dismissed and to take the user back to my homeViewController which is at tabBarController index:1. In addition, when the camera first loads, the timerLabel is displayed with the correct data but then quickly disappears. I feel it has something to do with my refreshLabel method but again, I do not clearly understand where I am going wrong. None of these things are working for me and I'm still very new to the programming world so help with any of these matters would be greatly appreciated. thanks!
#import "CameraViewController.h"
#import "FriendsViewController.h"
#import <mobileCoreServices/UTCoreTypes.h>
#interface CameraViewController ()
#end
#implementation CameraViewController
#synthesize titleLabel;
#synthesize timerLabel;
- (void)viewDidLoad
{ [super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (self.image == nil && [self.videoFilePath length] == 0) {
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
self.imagePickerController.allowsEditing = NO;
self.imagePickerController.videoMaximumDuration = 10;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;}
self.imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePickerController.sourceType];
[self presentViewController:self.imagePickerController animated:NO completion:nil];}
[[NSBundle mainBundle] loadNibNamed:#"OverlayView" owner:self options:nil];
self.overlayView.frame = CGRectMake(160,8,0,0);
self.imagePickerController.cameraOverlayView = self.overlayView;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt",
documentsDirectory];
NSString *name = [NSString stringWithFormat:#"%#/name.txt",
documentsDirectory];
NSError *fileError;
titleLabel.text = [NSString stringWithContentsOfFile:name
encoding:NSASCIIStringEncoding
error:&fileError];
timerLabel.text = [NSString stringWithContentsOfFile:deadline
encoding:NSASCIIStringEncoding
error:&fileError];
if(fileError.code == 0){
NSLog(#"deadline.txt was read successfully with these contents: %#,",
timerLabel.text);
NSLog(#"name.txt was read successfully with these contents: %#,",
titleLabel.text);}
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel)
userInfo:nil
repeats:YES];
}
-(void)refreshLabel;{
self.formatter = [NSDateFormatter new];
[self.formatter setDateFormat:#"dd:hh:mm:ss"];
NSDate *startDate = [self.formatter dateFromString:self.timerLabel.text];
NSDate *timeLeft = [startDate dateByAddingTimeInterval:-1];
NSTimeInterval totalCountdownInterval = -1;
NSTimeInterval elapsedTime = [timeLeft timeIntervalSinceNow];
NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;
if (remainingTime <= 0.0) {
//dismiss controller and set to homecontroller at tabBar index 1
}
self.timerLabel.text = [self.formatter stringFromDate:timeLeft];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Are you Sure?"
message:#"you can't come back"
delegate:self cancelButtonTitle:#"Back" otherButtonTitles:#"Yes", nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==1) {
[self.imagePickerController dismissViewControllerAnimated:NO completion:nil];
[self.tabBarController setSelectedIndex:1];
NSLog(#"Leave clicked");
}
else {
[self reset];
NSLog(#"cancel clicked");
}
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
}