I am using a web service used to display details about person and profile but I don't know how to display the data from web service to labels. I have worked with login validation using web service the code is as below
-(IBAction)login:(id)sender
{
NSString *username=userName.text;
NSString *password=passWord.text;
if ([username length]!=0&&[password length]!=0)
{
NSString *link=[NSStringstringWithFormat:#"http://www.abcd.com/XXX/YYY/Login.ashx/?Username=%#&Password=%#",username,password];
NSURL *URLGet= [NSURL URLWithString:link];
NSData* data = [NSData dataWithContentsOfURL:URLGet];
NSError* error;
XYZ Return array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if ([jasonReturnArray isEqual: #"UserId 4"])
{
Connections *view2=[[Connections alloc]initWithNibName:nil bundle:nil];
view2.modalTransitionStyle= UIModalTransitionStyleFlipHorizontal;
[self presentViewController:view2 animated:NO completion:nil];
NSLog(#"%#",jasonReturnArray);
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok"otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"
message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
It works fine but my doubt is
how to display the data from json web service to my designed labels
Create IBOutlet of your UILabel then set text value of your label as following
for (NSString * singleStringObject in jasonReturnArray)
{
yourLabel.text=[yourLabel.text stringByAppendingString:singleStringObject];
}
in case of single string you just set text of yourLabel without any loop.
Related
I am trying to convert my paid app to free version with IAP , so basically I need to check if users bought previous version then unlock IAP item , I am not sure I am doing right here or not ! even is it possible to check and track 'appStoreReceiptURL' in development process ? here is my code :
NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL];
NSLog(#"receiptUrl %#",[url path]);
NSError* err = nil;
if (![url checkResourceIsReachableAndReturnError:&err]){
SKReceiptRefreshRequest* request = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
request.delegate = self;
[request start];
}
-(void)requestDidFinish:(SKRequest*)request{
if([request isKindOfClass:[SKReceiptRefreshRequest class]]){
NSLog(#"YES, You purchased this app");
}
}
-(void)request:(SKRequest*)request didFailWithError:(NSError *)error{
NSLog(#"NO, you need to buy it ");
}
Now I am able to login with my Apple ID,and after I signed in it tells me YES, You purchased this app", and yes I really bought my app ! , I am going to make sure everything is alright .
Does this process should happen in every update ?
Here is a simple solution
#import <StoreKit/StoreKit.h>
Don't forget to add its delegates
<SKPaymentTransactionObserver, SKProductsRequestDelegate>
Payment Validation
- (IBAction)boughtIt:(id)sender {
NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL];
NSLog(#"receiptUrl %#",[url path]);
NSError* err = nil;
if (![url checkResourceIsReachableAndReturnError:&err]){
SKReceiptRefreshRequest* request = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
request.delegate = self;
[request start];
_activity.hidden = NO;
}
}
-(void)requestDidFinish:(SKRequest*)request{
if([request isKindOfClass:[SKReceiptRefreshRequest class]]){
NSLog(#"YES, You purchased this app");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Congrats !" message:#"Welcome To The World Of Dinosaurs" delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"isPurchased"];
[[NSUserDefaults standardUserDefaults] synchronize];
_activity.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)request:(SKRequest*)request didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !" message:#"It seems you did not purchase this app before, if you like to unlock all content and features please purchase Paleontologist Pack" delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
_activity.hidden = YES;
// [self dismissViewControllerAnimated:YES completion:nil];
NSLog(#"NO, you need to buy it ");
}
This works only if a user PURCHASED the application , it doesn't work for redeem codes
I am new to Xcode I need an app to send a email. Background: the destination email Id is typed in a text and by clicking the send button the message body Sample should go to the destination Email ID I tried this code in the function button clicked but it is not working when ever i try this code I get error in function can any one guide me with a step by step tutorial
mailTransfer[673:207] delegate - error(-5): timeout sending message
2014-07-05 10:54:05.393 mailTransfer[673:207] * stopping watchdog * I had added the SMTP files from google documents ... any other way to correct this code
- (IBAction)sendMessageInBack:(id)anObject
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Yours mail ids";
testMsg.toEmail = emailField.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Your mail ids";
testMsg.pass = #"id password";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,#"Sample",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
in SKPSMTPMessage.m
update the following line
CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
with
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Download SMTP framework and import SKPSMTPMessage class..
#import "SKPSMTPMessage.h"
-(void)sendEmailVideo:(NSString*)_toEmailAddress andCC:(NSString*)ccEmail
{
#try
{
// Message =[data getContentOfPanic];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail=#"nikki.varsha#gmail.com";//sender email address
emailMessage.toEmail=_toEmailAddress;
//receiver email address
emailMessage.relayHost=#"smtp.gmail.com";
//emailMessage.ccEmail =ccEmail;
emailMessage.requiresAuth = YES;
emailMessage.login = #"nikki.varsha#gmail.com"; //sender email address
emailMessage.pass = #"123";
//sender email password
emailMessage.subject =#"Panic Video Message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
Message,kSKPSMTPPartMessageKey,#"8bit", kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"Video.mov\"",kSKPSMTPPartContentTypeKey,
#"attachment;\r\n\tfilename=\"Video.mov\"",kSKPSMTPPartContentDispositionKey,[webData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts=[NSArray arrayWithObjects:plainPart,vcfPart,nil];
dispatch_queue_t backgroundVideoQueue = dispatch_queue_create("com.VideoQue", 0);
dispatch_sync(backgroundVideoQueue, ^{
[emailMessage send];
});
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Host" message:#"No Reciever Email Ids Available! " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
pragma mark - sendEmail delegate (SKPSMTPMessage)
-(void)messageSent:(SKPSMTPMessage *)message
{
NSLog(#"delegate - Email sent");
NSLog(#"Mesg %#",message);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"err=%#" ,message);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Unable to send email Please Check EmailId & Password"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
});
}
in SKPSMTPMessage.m file do change the following line
Remove this line
//CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
Add this line
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Thanks
I am new to iOS programming, and just want to do something fun.
I want to develop a mail client app for iPhone, it can add email accounts such as gmail and Yahoo and so on. I searched online for a while and also find some answers, before I dive into the details I just want someone who has similar experience give me some suggestions about which method is the best.
thanks
I have recently implemented gmail api to fetch gmail contacts and their email in my tableview. Gmail api is depricated, thats why you might have not got any proper documentation for that.
To implement gmail use libGDataTouchStaticLib.a library, with Gdata headers (search on google for that otherwise send me your email i will send you its zip).
The code to get gmail details are as follows
- (void)getGoogleContacts {
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
// request a whole buncha contacts; our service object is set to
// follow next links as well in case there are more than 2000
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket {
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = [txtUserName text];
NSString *password = [txtPasswrod text];
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
// contacts fetched callback
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[mutAryGoogleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
NSMutableDictionary *aDictContactDetails=[NSMutableDictionary dictionary];
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString* ContactEmail = [email address];
if (ContactEmail) {
[aDictContactDetails setObject:ContactEmail forKey:#"email"];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
if (ContactName) {
[aDictContactDetails setObject:ContactName forKey:#"friendName"];
}
[mutAryGoogleContacts addObject:aDictContactDetails];
}
}
//Push to next vc or do whatever you want
}
}
I am building an App according to this tutorial (http://bit.ly/NI9kQe) which uses a custom web api to connect to the web server. One of the requirements is to detect whether or not the Login or Register button has been tapped. This is done using a "tag" which has been set for the button in interface builder (the register button has a tag of 1).
The chunk of code sits inside the btnLoginRegisterTapped method as follows (the error occurs on the line -> NSString* command = (sender.tag==1)?#"register":#"login";):
- (IBAction)btnLoginRegisterTapped:(id)sender {
//form fields validation
if (fldUserName.text.length < 4 || fldPassword.text.length < 4) {
// [UIAlertView error:#"Enter username and password over 4 chars each."];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Enter username and password over 4 chars each." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
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 *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Password cannot be reset!" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
return;
}
//************ THIS IS WHERE THE ERROR OCCURS *****************//
//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) {
//handle the response
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
//success
[[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 *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Server down? Try Again" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
return;
}
}];
}
when I try to build the project (workspace actually) I get the error:
Property 'tag' not found on object of type '_strong id'
I am using xcode 5.0 deploying for iOS7.
Thanks,
Property syntax cannot be used with variables of the generic id type.
So either replace sender.tag by the method call [sender tag] or better,
use the actual type of the sender argument in the method definition:
- (IBAction)btnLoginRegisterTapped:(UIButton *)sender { ... }
Tip: When creating the action with "Control-Drag" in Xcode,
use the pop-up in the "Type" field to select the actual type of the sender.
Then the action method is created with the correct argument type.
Every time I try to save my NSManagedObjectContex, it takes 1-8 seconds each time. Here is my code:
- (IBAction)save
{
if (self.managedObjectContext == nil) {
self.managedObjectContext = [(RootAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
if (self.brandText.text.length == 0 || self.modelText.text.length == 0) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Please fill out the required fields" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(125, 40, 31, 7)];
NSString *path = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"bullet.png"]];
UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
[imageView setImage:bkgImg];
[alertView addSubview:imageView];
[alertView show];
} else {
Hand *a = [NSEntityDescription insertNewObjectForEntityForName:#"Hand" inManagedObjectContext:self.managedObjectContext];
a.brand = self.brandText.text;
a.caliber = self.cText.text;
self.managedObjectContext = self.app.managedObjectContext;
a.notes = self.notesView.text;
a.serialNumber = self.serialNumberText.text;
a.nickname = self.nicknameText.text;
a.model = self.modelText.text;
a.gunImage = self.image.image;
a.roundsFired = [NSString stringWithFormat:#"0"];
a.cleanRounds = [NSString stringWithFormat:#"500"];
a.showBadge = [NSNumber numberWithBool:YES];
[self dismissViewControllerAnimated:YES completion:nil];
NSError *error;
if (![self.managedObjectContext save:&error]) {
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an internal error. \n Please restart the app and try again, Thank You" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorAlert show];
}
}
}
The code just saves the all of the textFields text. What is the reason its so slow? Any help is greatly appreciated.
Based on your question is quite difficult to understand what is going on but I would modify the else statement as follows...
else {
Hand *a = [NSEntityDescription insertNewObjectForEntityForName:#"Hand" inManagedObjectContext:self.managedObjectContext];
a.brand = self.brandText.text;
a.caliber = self.cText.text;
// why this?
// self.managedObjectContext = self.app.managedObjectContext;
a.notes = self.notesView.text;
a.serialNumber = self.serialNumberText.text;
a.nickname = self.nicknameText.text;
a.model = self.modelText.text;
a.gunImage = self.image.image;
a.roundsFired = [NSString stringWithFormat:#"0"];
a.cleanRounds = [NSString stringWithFormat:#"500"];
a.showBadge = [NSNumber numberWithBool:YES];
NSError *error;
if (![self.managedObjectContext save:&error]) { // error during saving
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an internal error. \n Please restart the app and try again, Thank You" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorAlert show];
} else { // the save completes correctly, dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
}
If you want to monitor Core Data you should do it through Instrument. In addition you could set up Xcode as follows: XCode4 and Core Data: How to enable SQL Debugging.
Edit
Since the slow saving is due (based on your comment) to images, you should relies on these rules.
Core Data - Storing Images (iPhone)
Edit 2
Ok, since you don't know in advance about the size (in bytes) of your image, I really suggest to store the image in the filesystem and not in the Core Data store. In the db save only the path to your image. The image will be saved in background. This to prevent the UI to block.
Otherwise, if iOS 5 is the minimum requirement, use the External Storage flag.
How to enable External Storage for Binary Data in Core Data
Hope that helps.