Keyword Search in iOS - ios

I am new to iOS. I have a UITextfield and a Keyword Search Button. When ever I want to search a keyword from a service and press enter. Tt should display the related searched keyword from a service. Please help me to fix this issue? TIA!
- (IBAction)KeywordSearchClicked:(id)sender {
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
[self KeywordcallSignupProfileService:dict];
}
-(void)KeywordcallSignupProfileService:(NSMutableDictionary *)dict
{
[SVProgressHUD showWithStatus:#"" maskType:SVProgressHUDMaskTypeBlack]; // Progress
NSString * post = [[NSString alloc]initWithFormat:#"userId=%#&key_word%#",UserId,[dict objectForKey:#"key_word"]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.amarbiyashaadi.com/service/amarbiya-service.svc/userKeywordSearch/"]];
RBConnect = [[RBConnection alloc]init];
RBConnect.delegate = self;
[RBConnect postRequestForUrl:url postBody:post];
}
#pragma mark - MRConnection Delegate Methods
- (void)jsonData:(NSDictionary *)jsonDict
{
[SVProgressHUD dismiss];
NSMutableArray *jsonArr;
NSMutableDictionary *userDict,*dict;
NSArray *arr=[jsonDict allKeys];
jsonArr=[jsonDict objectForKey:#"DataTable"];
if (jsonArr.count>0) {
// Save credentials in user defaults
matchesProfileArr=[jsonArr mutableCopy];
DisplayTableViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"DisplayTableViewController"];
[self presentViewController:vc animated:YES completion:nil];
}
else
{
NSString *error=#"Somthing Went Wrong";
[SVProgressHUD showErrorWithStatus:error];
}
}

Related

Show AdMob Native Ads with MoPub (iOS)

I am integrating MoPub SDK to mediate ADs from the Google AdMob network. I can get the AD to show after implementing my own customEvent and Adapter, but i can't get the AD to handle click events on its own. As in when I click on the AdMob native AD, it won't direct me anywhere. When using Facebook and Flurry's CustomEvent and Adapter, clicks are handled automatically. Anyone have any experience on this subject?
Thanks in Advance. Code below:
MPGoogleAdMobCustomEvent
#interface MPGoogleAdMobCustomEvent()
#property(nonatomic, strong)GADAdLoader *loader;
#end
#implementation MPGoogleAdMobCustomEvent
- (void)requestAdWithCustomEventInfo:(NSDictionary *)info
{
MPLogInfo(#"MOPUB: requesting AdMob Native Ad");
NSString *adUnitID = [info objectForKey:#"adUnitID"];
if (!adUnitID) {
[self.delegate nativeCustomEvent:self didFailToLoadAdWithError:MPNativeAdNSErrorForInvalidAdServerResponse(#"MOPUB: No AdUnitID from GoogleAdMob")];
return;
}
self.loader = [[GADAdLoader alloc] initWithAdUnitID:adUnitID rootViewController:nil adTypes:#[kGADAdLoaderAdTypeNativeContent] options:nil];
self.loader.delegate = self;
GADRequest *request = [GADRequest request];
#if (TARGET_OS_SIMULATOR)
request.testDevices = #[ kGADSimulatorID ];
#endif
CLLocation *location = [[CLLocationManager alloc] init].location;
if (location) {
[request setLocationWithLatitude:location.coordinate.latitude
longitude:location.coordinate.longitude
accuracy:location.horizontalAccuracy];
}
request.requestAgent = #"MoPub";
[self.loader loadRequest:request];
}
- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeContentAd:(GADNativeContentAd *)nativeContentAd
{
MPLogDebug(#"MOPUB: Did receive nativeAd");
MPGoogleAdMobNativeAdAdapter *adapter = [[MPGoogleAdMobNativeAdAdapter alloc] initWithGADNativeContentAd:nativeContentAd];
adapter.url = nativeContentAd.advertiser;
MPNativeAd *interfaceAd = [[MPNativeAd alloc] initWithAdAdapter:adapter];
NSMutableArray *imageArray = [NSMutableArray array];
for (GADNativeAdImage *images in nativeContentAd.images) {
[imageArray addObject:images.imageURL];
}
[super precacheImagesWithURLs:imageArray completionBlock:^(NSArray *errors) {
if ([errors count]) {
[self.delegate nativeCustomEvent:self didFailToLoadAdWithError:errors[0]];
} else {
[self.delegate nativeCustomEvent:self didLoadAd:interfaceAd];
}
}];
}
- (void)adLoader:(GADAdLoader *)adLoader didFailToReceiveAdWithError:(GADRequestError *)error
{
MPLogDebug(#"MOPUB: AdMob ad failed to load with error (customEvent): %#", error.description);
[self.delegate nativeCustomEvent:self didFailToLoadAdWithError:error];
}
#end
MPGoogleAdMobNativeAdAdapter
#interface MPGoogleAdMobNativeAdAdapter()<GADNativeAdDelegate>
#property(nonatomic, strong)NSDictionary *properties;
#end
#implementation MPGoogleAdMobNativeAdAdapter
- (instancetype)initWithGADNativeContentAd:(GADNativeContentAd *)contentAD
{
self = [super init];
if (self) {
self.contentAd = contentAD;
self.contentAd.delegate = self;
self.properties = [self convertAssetsToProperties:contentAD];
}
return self;
}
- (NSDictionary *)convertAssetsToProperties:(GADNativeContentAd *)adNative
{
self.contentAd = adNative;
NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
if (adNative.headline) {
dictionary[kAdTitleKey] = adNative.headline;
}
if (adNative.body) {
dictionary[kAdTextKey] = adNative.body;
}
if (adNative.images[0]) {
dictionary[kAdMainImageKey] = ((GADNativeAdImage *)adNative.images[0]).imageURL.absoluteString;
}
if (adNative.callToAction) {
dictionary[kAdCTATextKey] = adNative.callToAction;
}
return [dictionary copy];
}
#pragma mark MPNativeAdAdapter
- (NSTimeInterval)requiredSecondsForImpression
{
return 0.0;
}
- (NSURL *)defaultActionURL
{
return nil;
}
- (BOOL)enableThirdPartyClickTracking
{
return YES;
}
- (void)willAttachToView:(UIView *)view
{
self.contentAd.rootViewController = [self.delegate viewControllerForPresentingModalView];
}
- (void)didDetachFromView:(UIView *)view
{
self.contentAd.rootViewController = nil;
}
#pragma mark GADNativeAdDelegate
- (void)nativeAdWillPresentScreen:(GADNativeAd *)nativeAd
{
if ([self.delegate respondsToSelector:#selector(nativeAdWillPresentModalForAdapter:)]) {
[self.delegate nativeAdWillPresentModalForAdapter:self];
}
}
- (void)nativeAdDidDismissScreen:(GADNativeAd *)nativeAd
{
if ([self.delegate respondsToSelector:#selector(nativeAdDidDismissModalForAdapter:)]) {
[self.delegate nativeAdDidDismissModalForAdapter:self];
}
}
- (void)nativeAdWillLeaveApplication:(GADNativeAd *)nativeAd
{
if ([self.delegate respondsToSelector:#selector(nativeAdWillLeaveApplicationFromAdapter:)]) {
[self.delegate nativeAdWillLeaveApplicationFromAdapter:self];
}
}
#end
`
If you are having your custom UI for AdMob Ad's, then there will be a button which you will be using for callToAction part.
First of all you need to add a selector to detect action of click, to do add the selector for that button
[callToActionButton addTarget:self action:#selector(adCalled:) forControlEvents:UIControlEventTouchUpInside];
After that implement the adCalled method to get the click & call the method further, below is the code for your reference
Below is the example which I have used to get the ad object from my collection view & then I am redirecting it.
- (void)adCalled:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:mainCollectionView]; // Get the button position
NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:buttonPosition]; // Get the index path of button so that I can retrieve the correct ad object
id selectedAd = [adArray objectAtIndex:indexPath.row];
if ([selectedAd isKindOfClass:[GADNativeContentAd class]]) {
NSString *url = [selectedAd valueForKey:#"googleClickTrackingURLString"];
NSLog(#"URL is :%#", url);
NSURL *googleUrl = [NSURL URLWithString:url];
if ([[UIApplication sharedApplication] canOpenURL: googleUrl]) {
[[UIApplication sharedApplication] openURL:googleUrl];
}
}
}
Using this I can open the link n web using the google tracking url.
Hope this helps.

Initialize UITableview with Contents from XML but can't show progress with UIAlertview

I am writing an app, which is getting data from the net using XML. It is a master-detail-app which is fetching data for the master-table and after selecting one item from the master-Table it fills the data for the detailview(s) using another network-access.
I would like to present an alert in order to show the user that the app is busy accessing the net or busy calculating. So I would present the view from the UIAlertController before the calculation / network access starts and dismiss the view when the activity has completed
Problem is: I don't know where to put this call to show / dismiss the UIAlertcontroller view.
Putting the activity code into ViewWillAppear shows and dismisses the alertview BEFORE the network-access... Putting everything into ViewDidLoad seems not the way to go.
- (void) viewWillAppear:(BOOL)animated
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Working"
message:#"Working on it"
preferredStyle:UIAlertControllerStyleAlert];
self.objects = [[NSMutableArray alloc] init];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:#"Accounts"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
NSURL *url;
if ([self getSession])
{
NSMutableString *URLstring = [NSMutableString stringWithString:#"https://XXXXXXXXXXXXXXX.xml?session="];
[self presentViewController:alert animated:YES completion:nil];
[URLstring appendString:[[DataStore getData]SessionString]];
url = [NSURL URLWithString:URLstring];
self.myXXXXXXParserAlleKontenXMLDelegate = [[KontenParserDelegate alloc] init];
self.xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
self.xmlParser.delegate = self.myfxbookParserAlleKontenXMLDelegate;
if ([self.xmlParser parse])
{
[self.objects removeAllObjects];
for(int i=0; i< [self.XXXXXXXXXrAlleKontenXMLDelegate.allAccounts count];i++)
{
[self.objects addObject : [self.myfxbookParserAlleKontenXMLDelegate.allAccounts objectAtIndex:i]];
}
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey: #"name" ascending: YES];
[self.objects sortUsingDescriptors:#[sort]];
[self.tableView reloadData];
[self dismissViewControllerAnimated:YES completion:nil];
// Do any additional setup after loading the view, typically from a nib.
}
}
}
Added After some discussions I added some new framework "SVProgressHUD" and entered the following code into "ViewWillAppear" where [self parserstuff] contains all the XML parsing..
[SVProgressHUD show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self parserstuff];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
});
This leaves me with a HUD-Display showing up while parsing XML but the resulting Tableview does not show data but is empty... After switching to DISPATCH_SYNC it works.
Solution would be
1) Put code in ViewDidLoad
2) encapsulate Code between "SVProgressHUD show" and "dismiss" with dispatch_async
as in
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD show];
[self parserstuff];
[self fillComparatorParameters:nil];
[self.tableView reloadData];
[SVProgressHUD dismiss];
// }];
});

MFMailComposeViewController dismissed very slow after clicked send button

I have a bit of a strange problem. I am trying to send in-app email. So, I use MFMailComposeViewController for that.And I have realized MFMailComposeViewControllerDelegate.
When I click the send button, it should be dismissed immediately.In debug mode,it works well,BUT,in release mode,it is extremely slow so that user may click send button more than one time and the mail will be sent more than one time.
I have been confused for five days.
Anyone can help me ?
My code:
-(void)sendEMail
{
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
if ([mailClass canSendMail])
{
[self displayComposerSheet];
//[self launchMailAppOnDevice];
} else{
[self launchMailAppOnDevice];
}
} else {
[self launchMailAppOnDevice];
}
}
//可以发送邮件的话
-(void)displayComposerSheet
{
//mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
//设置主题
[mailPicker setSubject: kEmailSubject];
// 添加发送者
NSArray *toRecipients = [NSArray arrayWithObject: kToRecipient];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com", nil];
[mailPicker setToRecipients: toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// 添加图片
// UIImage *addPic = [UIImage imageNamed: #"123.jpg"];
// NSData *imageData = UIImagePNGRepresentation(addPic); // png
// NSData *imageData = UIImageJPEGRepresentation(addPic, 1); // jpeg
// [mailPicker addAttachmentData: imageData mimeType: #"" fileName: #"123.jpg"];
NSString *emailBody = kEmailBody;
[mailPicker setMessageBody:emailBody isHTML:YES];
[self presentViewController:mailPicker animated:YES completion:nil];
}
-(void)sendMailBtnCLicked{
[mailPicker dismissViewControllerAnimated:YES completion:nil];
}
-(void)launchMailAppOnDevice
{
NSString *recipients = kToRecipient;
NSString *subject = kEmailSubject;
//#"mailto:first#example.com?cc=second#example.com,third#example.com&subject=my email!";
NSString *body = kEmailBody;
NSString *email = [NSString stringWithFormat:#"mailto:%#?subject=%#&body=%#", recipients, subject,body];
email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
if (result == MFMailComposeResultSent) {
[AccountManager sharedManager].isSentMail = YES;
}
[controller dismissViewControllerAnimated:YES completion:nil];
//[self dismissModalViewControllerAnimated:YES];
}
Stop other threads running background.
After the mail sent, restart them.

Send Contact Form Fields in Email

I have a contact form made of text fields (5 fields) that I would like to send via email to a single email address. How do I do this in xCode?
For anyone stumbling across this question, you can use this drop-in iOS contact form.
This fit my needs well, it uses a PHP component to actually send the email. (an example script is included in the sample project.
I posted it to Github here:
https://github.com/mikecheckDev/MDContactForm
The linked post has a similar answer, but I'm adding my code since it checks for canSendMail already. I also left in a bunch of commented code that makes it easy to add other stuff to the email.
Note that this is substantially easier if you are only targeting iOS 5.
I have a free app, QCount, that uses this code. Indeed, I hope I stripped everything custom from my copy-and-paste :-) http://itunes.apple.com/ng/app/qcount/id480084223?mt=8
Enjoy,
Damien
In your .h:
#import <MessageUI/MessageUI.h>
Methods in your .m:
- (void)emailLabelPressed { // or whatever invokes your email
// Create a mail message in the user's preferred mail client
// by opening a mailto URL. The extended mailto URL format
// is documented by RFC 2368 and is supported by Mail.app
// and other modern mail clients.
//
// This routine's prototype makes it easy to connect it as
// the action of a user interface object in Interface Builder.
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}
-(void)displayComposerSheet {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Your Form Subject"];
// Take screenshot and attach (optional, obv.)
UIImage *aScreenshot = [self screenshot];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(aScreenshot)];
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"screenshot"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"first#example.com", nil];
// NSArray *ccRecipients = [[NSArray alloc] init];
// NSArray *bccRecipients = [[NSArray alloc] init];
// NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
// NSArray *bccRecipients = [NSArray arrayWithObjects:#"fourth#example.com", nil];
[picker setToRecipients:toRecipients];
// [picker setCcRecipients:ccRecipients];
// [picker setBccRecipients:bccRecipients];
// Attach an image to the email.
/* NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano"
ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png"
fileName:#"ipodnano"];
*/
// Fill out the email body text.
// NSString *emailBody = #"Use this for fixed content.";
NSMutableString *emailBody = [[NSMutableString alloc] init];
[emailBody setString: #"Feedback"];
// programmatically add your 5 fields of content here.
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]) {
[self presentViewController:picker animated:YES completion:nil];
} else {
[self presentModalViewController:picker animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
-(void)launchMailAppOnDevice {
NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *body = #"&body=Feedback";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

IOS Queue Asynchronous downloads

I am facing an issue making a queue of asynchronous downloads of 3 files.
I would like when I finish to download and saved the first files to start to download the second one then third one ...
For the moment I am using 3 IBAction to download into Documents folder and it work perfectly, but to make it automatically for all files didn´t work.
What is the best way to implement the download queue of this files ?
I know i have to had statements on didReceiveData but I need help to make it working.
This is the code I am using :
// Download song 1
- (IBAction)download {
[self performSelector:#selector(downloadmusic) withObject:nil afterDelay:0.0];
}
- (void)downloadmusic
{
self.log = [NSMutableString string];
[self doLog:#"1/13"];
// Retrieve the URL string
int which = [(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex];
NSArray *urlArray = [NSArray arrayWithObjects: SONG1_URL, nil];
NSString *urlString = [urlArray objectAtIndex:which];
// Prepare for download
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Set up the Download Helper and start download
[DownloadHelper sharedInstance].delegate = self;
[DownloadHelper download:urlString];
}
// Download song 2
- (void)downloadmusic2
{
self.log = [NSMutableString string];
[self doLog:#"2/13"];
// Retrieve the URL string
int which = [(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex];
NSArray *urlArray = [NSArray arrayWithObjects: SONG2_URL, nil];
NSString *urlString = [urlArray objectAtIndex:which];
// Prepare for download
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Set up the Download Helper and start download
[DownloadHelper sharedInstance].delegate = self;
[DownloadHelper download:urlString];
}
// Download song 3
- (void)downloadmusic3
{
self.log = [NSMutableString string];
[self doLog:#"3/13"];
// Retrieve the URL string
int which = [(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex];
NSArray *urlArray = [NSArray arrayWithObjects: SONG3_URL, nil];
NSString *urlString = [urlArray objectAtIndex:which];
// Prepare for download
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Set up the Download Helper and start download
[DownloadHelper sharedInstance].delegate = self;
[DownloadHelper download:urlString];
}
- (void) doLog: (NSString *) formatstring, ...
{
va_list arglist;
if (!formatstring) return;
va_start(arglist, formatstring);
NSString *outstring = [[[NSString alloc] initWithFormat:formatstring arguments:arglist] autorelease];
va_end(arglist);
[self.log appendString:outstring];
[self.log appendString:#"\n"];
[textView setText:self.log];
}
- (void) restoreGUI
{
self.navigationItem.rightBarButtonItem = BARBUTTON(#"Get Data", #selector(action:));
if ([[NSFileManager defaultManager] fileExistsAtPath:DEST_PATH])
self.navigationItem.leftBarButtonItem = BARBUTTON(#"Play", #selector(startPlayback:));
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[(UISegmentedControl *)self.navigationItem.titleView setEnabled:YES];
[progress setHidden:YES];
}
- (void) dataDownloadAtPercent: (NSNumber *) aPercent
{
[progress setHidden:NO];
[progress setProgress:[aPercent floatValue]];
}
- (void) dataDownloadFailed: (NSString *) reason
{
[self restoreGUI];
if (reason) [self doLog:#"Download failed: %#", reason];
}
- (void) didReceiveFilename: (NSString *) aName
{
self.savePath = [DEST_PATH stringByAppendingString:aName];
}
- (void) didReceiveData: (NSData *) theData
{
if (![theData writeToFile:self.savePath atomically:YES])
[self doLog:#"Error writing data to file"];
[theData release];
[self restoreGUI];
[self doLog:#"Download succeeded"];
//[self performSelector:#selector(downloadmusic2) withObject:nil afterDelay:1.0];
//[self performSelector:#selector(downloadmusic3) withObject:nil afterDelay:1.0];
}
From within your controller, create three blocks and copy them to an array, which will serve as your queue. This array will need to be stored as an instance variable so that it can be accessed by later invocations of methods in your controller class. Each of the three blocks should create and execute an NSURLConnection which asynchronously downloads the appropriate file. The delegate of each NSURLConnection can be your controller, and it should implement the -connectionDidFinishLoading: delegate method. From this method, call a method which pops the first block off the queue and executes it.
Then just call the method for the first time to start the process. Obviously there is some edge-case and error handling that you need to provide, but this is the basic idea.

Resources