Search Results

Search found 2441 results on 98 pages for 'delegate'.

Page 36/98 | < Previous Page | 32 33 34 35 36 37 38 39 40 41 42 43  | Next Page >

  • How should I properly format this code?

    - by ct2k7
    Hi, I've a small issue here. I am using an if statement with UIAlertView and I have two situations, both result in UIAlertViews. However, in one situation, I want to dismiss just the UIAlertView, the other, I want the UIAlertView to be dismissed and view to return to root view. This code describes is: if([serverOutput isEqualToString:@"login.true"]){ [Alert dismissWithClickedButtonIndex:0 animated:YES]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; UIAlertView *success = [[UIAlertView alloc] initWithTitle:@"Success" message:@"The transaction was a success!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [success show]; [success release]; } else { UIAlertView *failure = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"The transaction failed. Contact sales operator!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [failure show]; [failure release]; } } -(void)alertView: (UIAlertView *)success clickedButtonAtIndex: (NSInteger)buttonIndex{ switch(buttonIndex) { case 0: { [self.navigationController popToRootViewControllerAnimated:YES]; } } } So, in both cases, they follow the above action, but obviously, that's not what I want. Any ideas on what I do here?

    Read the article

  • How stop mp3 playing started with audioplayer

    - by bucche
    Hi, My application consists of a table view. row1, row2, row3.... When a cell is touched a different mp3 starts to play (row1.mp3, row2.mp3, row3.mp3....). it works! but i have a problem: i am not able to stop previous mp3, so if i touch a second cell i have 2 mp3s playing... if i touch a third cell i have 3 mp3s and so on... i want to stop mp3 that started before and play mp3 that is related to touched cell... during my tries, i created a variable to show some alerts if the player plays or not and when i am "inside the if" i used [myAudioPlayer stop].. i see the correct alert but mp3 doesn't stop. here is my code - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *elementi = [[array objectAtIndex:indexPath.row] componentsSeparatedByString:@"|"]; NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath],[elementi objectAtIndex:1]]]; NSError *error; myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; myAudioPlayer.numberOfLoops = -1; if (inEsecuzione == 0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"1" message:@"1" delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil]; [alert show]; [alert release]; [myAudioPlayer play]; inEsecuzione = 1; } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"2" message:@"2" delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil]; [alert show]; [alert release]; [myAudioPlayer stop]; inEsecuzione = 0; } } as i wrote before, i am not able to stop previous mp3

    Read the article

  • callbacks via objective-c selectors

    - by codemonkey
    I have a "BSjax" class that I wrote that lets me make async calls to our server to get json result sets, etc using the ASIHTTPRequest class. I set it up so that the BSjax class parses my server's json response, then passes control back to the calling view controller via this call: [[self delegate] performSelectorOnMainThread:@selector(bsRequestFinished:) withObject:self waitUntilDone:YES]; ... where "bsRequestFinished" is the callback method in the calling view controller. This all worked fine and well until I realized that some pages are going to need to make different types of requests... i.e. I'll want to do different types of things in that callback function depending on which type of request was made. To me it seems like being able to pass different callback function names to my BSjax class would be the cleanest fix... but I'm having trouble (and am not even sure if it's possible) to pass in a variable that holds the callback function name and then replace the call above with something like this: [[self delegate] performSelectorOnMainThread:@selector(self.variableCallbackFunctionName) withObject:self waitUntilDone:YES]; ... where "self.variableCallbackFunctionName" is set by the calling view controller when it calls BSjax to make a new request. Is this even possible? If so, advisable? If not, alternatives? EDIT: Note that whatever fix I arrive at will need to take into account the reality that this class is making async requests... so I need to make sure that the callback function processing is correctly tied to the specific requests... as I can't rely on FIFO processing sequence.

    Read the article

  • iOS: display modal view over the top of a UIWebView

    - by Sly
    Is it possible to display a modal view over the top of a UIWebView? I have a UIViewController that loads a WebView. I then want to push a Modal View Controller over the top so that a modal view covers up the WebView temporarily... The WebView is working fine; here's how it's loaded in the View Controller: - (void)loadView { // Initialize webview and add as a subview to LandscapeController's view myWebView = [[[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; myWebView.scalesPageToFit = YES; myWebView.autoresizesSubviews = YES; myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); myWebView.delegate = self; self.view = myWebView; } If I attempt to load a Modal View controller from within viewDidLoad, however, no modal view appears: - (void)viewDidLoad { [super viewDidLoad]; // Edit dcftable.html with updated figures NSMutableString *updated_html = [self _updateHTML:@"dcftable"]; // Load altered HTML file as an NSURL request [self.myWebView loadHTMLString:updated_html baseURL:nil]; // If user hasn't paid for dcftable, then invoke the covering modal view if (some_condition) { LandscapeCoverController *landscapeCoverController = [[[LandscapeCoverController alloc] init] autorelease ]; [self presentModalViewController:landscapeCoverController animated:YES]; } } I suspect that there's something that needs to be done with the UIWebView delegate to get it to receive the new modal view...but can't find any discussion or examples of this anywhere...again, the objective is to invoke a modal view that covers over the top of the WebView. Thanks for any thoughts in advance!

    Read the article

  • xml parser not able to read all the nodes of the xml

    - by pankaj
    Hi i am trying to get values from all the nodes of a xml returned from a web service. But my code only reads first node, it does not read it further. code: -(void)parseData{ NuanceAppDelegate *appDel = (NuanceAppDelegate *)[[UIApplication sharedApplication] delegate]; NSString *url = @"http://cmweb.bpomatrix.net/SmartPhoneService.svc/login/"; url = [[[url stringByAppendingString:UserName] stringByAppendingString:@"/"] stringByAppendingString:Password]; url = [[url stringByAppendingString:@"/"] stringByAppendingString:appDel.CPAID]; NSLog(@"log: @%",url); NSURL *loginURL = [NSURL URLWithString:url]; NSXMLParser *home_Parser = [[NSXMLParser alloc] initWithContentsOfURL:loginURL]; [home_Parser setDelegate:self]; dict = [[NSMutableDictionary alloc] init]; [home_Parser parse]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{ if([elementName isEqualToString:@"Address"]) addressFound = TRUE; if([elementName isEqualToString:@"Name"]) nameFound = TRUE; if([elementName isEqualToString:@"LoyaltyNum"]) loyaltyNumFound = TRUE; if([elementName isEqualToString:@"City"]) cityFound = TRUE; if([elementName isEqualToString:@"Province"]) proFound = TRUE; if([elementName isEqualToString:@"Zip"]) zipFound = TRUE; //NSLog(@"Response %@",responseFound); } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ if(addressFound) { [dict setObject:string forKey:@"address"]; addressFound = FALSE; } else if(nameFound) { [dict setObject:string forKey:@"name"]; nameFound = FALSE; } else if(loyaltyNumFound) { [dict setObject:string forKey:@"loyaltyNum"]; loyaltyNumFound = FALSE; } else if(cityFound) { [dict setObject:string forKey:@"city"]; cityFound = FALSE; } else if(proFound) { [dict setObject:string forKey:@"province"]; proFound = FALSE; } else if(zipFound) { [dict setObject:string forKey:@"zip"]; zipFound = FALSE; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"clsUserProfile"]) { [self parsingOver]; } } -(void)parsingOver { NuanceAppDelegate *appDel = (NuanceAppDelegate *)[[UIApplication sharedApplication] delegate]; appDel.dictProfile = dict; }

    Read the article

  • How do you populate a NSArrayController with CoreData rows programmatically?

    - by Andrew McCloud
    After several hours/days of searching and diving into example projects i've concluded that I need to just ask. If I bind the assetsView (IKImageBrowserView) directly to an IB instance of NSArrayController everything works just fine. - (void) awakeFromNib { library = [[NSArrayController alloc] init]; [library setManagedObjectContext:[[NSApp delegate] managedObjectContext]]; [library setEntityName:@"Asset"]; NSLog(@"%@", [library arrangedObjects]); NSLog(@"%@", [library content]); [assetsView setDataSource:library]; [assetsView reloadData]; } Both NSLogs are empty. I know i'm missing something... I just don't know what. The goal is to eventually allow multiple instances of this view's "library" filtered programmatically with a predicate. For now i'm just trying to have it display all of the rows for the "Asset" entity. Addition: If I create the NSArrayController in IB and then try to log [library arrangedObjects] or manually set the data source for assetsView I get the same empty results. Like I said earlier, if I bind library.arrangedObjects to assetsView.content (IKImageBrowserView) in IB - with same managed object context and same entity name set by IB - everything works as expected. - (void) awakeFromNib { // library = [[NSArrayController alloc] init]; // [library setManagedObjectContext:[[NSApp delegate] managedObjectContext]]; // [library setEntityName:@"Asset"]; NSLog(@"%@", [library arrangedObjects]); NSLog(@"%@", [library content]); [assetsView setDataSource:library]; [assetsView reloadData]; }

    Read the article

  • Stop NSXMLParser Instance from Causing _NSAutoreleaseNoPool

    - by PF1
    Hi Everyone: In my iPhone application, I have an instance of NSXMLParser that is set to a custom delegate to read the XML. This is then moved into its own thread so it can update the data in the background. However, ever since I have done this, it has been giving me a lot of _NSAutoreleaseNoPool warnings in the console. I have tried to add a NSAutoreleasePool to each of my delegate classes, however, this hasn't seemed to solve the problem. I have included my method of creating the NSXMLParser in case that is at fault. NSURL *url = [[NSURL alloc] initWithString:@"http://www.mywebsite.com/xmlsource.xml"]; NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; CustomXMLParser *parser = [[CustomXMLParser alloc] init]; parser.managedObjectContext = self.managedObjectContext; parser = [parser initXMLParser]; [xmlParser setDelegate:parser]; [NSThread detachNewThreadSelector:@selector(parse) toTarget:xmlParser withObject:nil]; If anyone has any ideas to get rid of this problem, I would really appreciate it. Thanks.

    Read the article

  • Navigation Controller not Pushing/Popping View Controllers

    - by senfo
    I'm working on a view-based iPhone app that has the following flow: search - (list | map) - details To accomplish the transitions between views, I have a UINavigationController, with the search view controller being the root. After a user performs a search, I transition to a view with a segmented control, which acts as a tab to switch between the list and map functionality (per a suggestion from a related question I had). This view contains a UIViewController, which allows me to switch between the list/map view when a user taps the segmented control. I'm fine up until this point. As you can see from the above mentioned flow, I would like to provide the ability to transition into a details view. Each row of my table in the list view contains a details disclosure button for allowing the user to drill down into a details view. The problem is, when I try to push the details view onto the navigation stack, nothing happens. Below is the delegate method (from my list view controller) to handle the details disclosure button being tapped. I've set up break points, so I know the code is running. The navigation controller simply doesn't want to push the detailsController onto the stack (my guess is that I don't have a pointer to the correct UINavigationController). - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { if (detailController == nil) { detailController = [[DetailsViewController alloc] init]; } [self.navigationController pushViewController:detailController animated:YES]; } Assuming I was probably missing a pointer to the navigation controller, I exposed a UINavigation property on my list and map views (navigationController is readonly) and initialized them with a pointer to the navigation controller from my SwitchViewController (the view responsible for switching between list/map views when a user changes the value of the segmented control). Unfortunately, this did not solve the problem. Am I on the right track? If so, how do I see to it that my view has a pointer to the correct navigation controller? Should I add a delegate, which allows me to call a function in the SwitchViewController that transitions into the details view (this seems messy)?

    Read the article

  • Refreshing a MKMapView when the user location is updated or using default values

    - by koichirose
    I'm trying to refresh my map view and load new data from the server when the device acquires the user location. Here's what I'm doing: - (void)viewDidLoad { CGRect bounds = self.view.bounds; mapView = [[MKMapView alloc] initWithFrame:bounds]; mapView.showsUserLocation=YES; mapView.delegate=self; [self.view insertSubview:mapView atIndex:0]; [self refreshMap]; } - (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation { //this is to avoid frequent updates, I just need one position and don't need to continuously track the user's location if (userLocation.location.horizontalAccuracy > self.myUserLocation.location.horizontalAccuracy) { self.myUserLocation = userLocation; CLLocationCoordinate2D centerCoord = { userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude }; [theMapView setCenterCoordinate:centerCoord zoomLevel:10 animated:YES]; [self refreshMap]; } } - (void)refreshMap { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; [self.mapView removeAnnotations:self.mapView.annotations]; //default position NSString *lat = @"45.464161"; NSString *lon = @"9.190336"; if (self.myUserLocation != nil) { lat = [[NSNumber numberWithDouble:myUserLocation.coordinate.latitude] stringValue]; lon = [[NSNumber numberWithDouble:myUserLocation.coordinate.longitude] stringValue]; } NSString *url = [[NSString alloc] initWithFormat:@"http://myserver/geo_search.json?lat=%@&lon=%@", lat, lon]; NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; [url release]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; } I also have a - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data, to create and add the annotations. Here's what happens: sometimes I get the location after a while, so I already loaded data close to the default location. Then I get the location and it should remove the old annotations and add the new ones, instead I keep seeing the old annotations and the new ones are added anyway (let's say I receive 10 annotations each time, so it means that I have 20 on my map when I should have 10). What am I doing wrong?

    Read the article

  • iPhone dev: UIBarButtonItem or title not showing up in NavigationBar

    - by IceMan85
    Hello everyone, here my problem. I have a NavigationBar at the top, a TabBar at the bottom and a TableView at the center of the screen. Very normal situation. I set it all up in IB and I have set this in the app delegate : ExpensesListNavController *expensesListNavController; This in order to be able to add new views to the stack. I need to have 3 levels: - list of items in a TableView - OK - firstLevel: once pressed one cell a view is added to the stack - OK - second level: one pressed the "modify" button on the navBar on the firstLevel I want to show a new view that can be customized by the user. My Problem is coming when trying to add the "Modify" button in the "firstLevelView". Here-below my code -(IBAction) modify:(id)sender { if (editableDetailViewController == nil) { editableDetailViewController = [[editableDetailViewController alloc] init]; } editableDetailViewController.expense = expense; [appDelegate.expensesListNavController pushViewController:editableDetailViewController animated:YES]; editableDetailViewController = nil; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; appDelegate = [[UIApplication sharedApplication] delegate]; UIBarButtonItem *modifyButton = [[UIBarButtonItem alloc] initWithTitle:@"Modify" style:UIBarButtonItemStylePlain target:self action:@selector(modify:)]; appDelegate.expensesListNavController.navigationItem.rightBarButtonItem = modifyButton; appDelegate.expensesListNavController.navigationItem.title = @"Titoloooo"; NSLog(@"NavBar button has just been set !!"); [modifyButton release]; Nothing is being showed, neither title nor the button. Do you have any idea of what is happening ?? I really cannot figure out !!! Thanks a lot in advance, AM

    Read the article

  • Namespace scoped aliases for generic types in C#

    - by TN
    Let's have a following example: public class X { } public class Y { } public class Z { } public delegate IDictionary<Y, IList<Z>> Bar(IList<X> x, int i); public interface IFoo { // ... Bar Bar { get; } } public class Foo : IFoo { // ... public Bar Bar { get { return null; //... } } } void Main() { IFoo foo; //= ... IEnumerable<IList<X>> source; //= ... var results = source.Select(foo.Bar); } The compiler says: The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. It's because, it cannot convert Bar to Func<IList<X>, int, IDictionary<Y, IList<Z>>>. It would be great if I could create type namespace scoped type aliases for generic types in C#. Then I would define Bar not as a delegate, but rather I would define it as an namespace scoped alias for Func<IList<X>, int, IDictionary<Y, IList<Z>>>. public alias Bar = Func<IList<X>, int, IDictionary<Y, IList<Z>>>; I could then also define namespace scoped alias for e.g. IDictionary<Y, IList<Z>>. And if used appropriately:), it will make the code more readable. Now I have inline the generic types and the real code is not well readable:( Have you find the same trouble:)? Is there any good reason why it is not in C# 3.0? Or there is no good reason, it's just matter of money and/or time? EDIT: I know that I can use using, but it is not namespace based - not so convenient for my case.

    Read the article

  • Events convention - I don't get it

    - by bobjink
    My class with an event: public class WindowModel { public delegate void WindowChangedHandler(object source, WindowTypeEventArgs e); public event WindowChangedHandler WindowChanged; public void GotoWindow(WindowType windowType) { this.currentWindow = windowType; this.WindowChanged.Invoke(this, new WindowTypeEventArgs(windowType)); } } Derived event class: public class WindowTypeEventArgs : EventArgs { public readonly WindowType windowType; public WindowTypeEventArgs(WindowType windowType) { this.windowType = windowType; } } Some other class that register it to the event: private void SetupEvents() { this.WindowModel.WindowChanged += this.ChangeWindow; } private void ChangeWindow(object sender, WindowTypeEventArgs e) { //change window } What have I gained from following the .Net convention? It would make more sense to have a contract like this public delegate void WindowChangedHandler(WindowType windowType); public event WindowChangedHandler WindowChanged; Doing it this way, I don't need to create a new class and is easier to understand. I am not coding a .Net library. This code is only going to be used in this project. I like conventions but am I right when I say that in this example it does not make sense or have i missunderstood something?

    Read the article

  • problems getting HTTPRiot working

    - by bwizzy
    I've got an iphone app where I'm trying to use HTTPRiot to make some API calls to a web app. Problem is I can't see that none of the HTTPRiot delegate methods are being called. I've got a log in all the delegate methods, and I'm also looking at the webserver log. I see that the URL is being hit. //API.h #import <Foundation/Foundation.h> #include <HTTPRiot/HTTPRiot.h> @interface API : HRRestModel { } +(void)runTest; @end //API.m #import "API.h" @implementation API + (void)initialize { NSLog(@"api initialize"); [self setDelegate:self]; [self setBaseURL:[NSURL URLWithString:@"http://localhost:3000/api"]]; [self setBasicAuthWithUsername:@"demo" password:@"123456"]; NSDictionary *params = [NSDictionary dictionaryWithObject:@"1234567" forKey:@"api_key"]; [self setDefaultParams:params]; }//end initialize +(void)runTest { NSLog(@"api run test"); // Would send a request to http://localhost:1234/api/people/1?api_key=1234567 [self getPath:@"/save_diet" withOptions:nil object:nil]; } +(void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object { NSLog(@"didReturnResource"); } +(void)restConnection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response object:(id)object { NSLog(@"didReceiveResponse"); } +(void)restConnection:(NSURLConnection *)connection didReceiveParseError:(NSError *)error responseBody:(NSString *)body object:(id)object { NSLog(@"didReceiveParseError"); } +(void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object { NSLog(@"didReceiveError"); } +(void)restConnection:(NSURLConnection *)connection didFailWithError:(NSError *)error object:(id)object { NSLog(@"didFailWithError"); } @end //test code [API runTest]; //log output

    Read the article

  • EXC_BAD_ACCESS in NSURLConnection: how to debug?

    - by baswell
    I have an iPhone app that downloads URLs. (PDFs to display) Easy: self.conn = [NSURLConnection connectionWithRequest:self.request delegate:self]; where self.conn is a retained property. For specific URLs, this throws EXC_BAD_ACCESS. The URL is valid and is constructed in the same way as URLs that do work. (90% of URLs are fine) These ones work: http://www.airservicesaustralia.com/publications/current/ersa/FAC_YARG_11-Mar-2010.pdf http://www.airservicesaustralia.com/publications/current/ersa/FAC_YARK_11-Mar-2010.pdf These don't: http://www.airservicesaustralia.com/publications/current/ersa/FAC_YAMK_11-Mar-2010.pdf http://www.airservicesaustralia.com/publications/current/ersa/FAC_YATN_11-Mar-2010.pdf Spot the difference? Yeah, me neither. Also no difference in response headers from the server for them. To clarify, the ones that work ALWAYS work, the ones that don't NEVER work. So not some random release/retain issue it seems. For the ones that don't work, none of the methods in my delegate are ever called, it fails hard before that. And with no error message, just EXC_BAD_ACCESS. Sooo.... Any way to debug what is going on inside NSURLConnection?

    Read the article

  • VB.net avoiding cross thread exception with extension method

    - by user574632
    Hello I am trying to implement a solution for updating form controls without using a delegate. I am attempting to use the 1st solution on this page: http://www.dreamincode.net/forums/blog/143/entry-2337-handling-the-dreaded-cross-thread-exception/ Imports System.ComponentModel Imports System.Runtime.CompilerServices Public Module MyInvoke <Extension()> _ Public Sub CustomInvoke(Of T As ISynchronizeInvoke)(ByVal control As T, ByVal toPerform As Action(Of T)) If control.InvokeRequired Then control.Invoke(toPerform, New Object() {control}) toPerform(control) End If End Sub End Module The site gives this as example of how to use: Label1.CustomInvoke(l => l.Text = "Hello World!") But i get 'l' is not declared error. As you can see im very new to VB or any OOP. I can get the second solution on that page to work (using delegates) but i have quite a few things to do in this thread and it seems like i would need to write a new delegate sub for each thing, which seems wasteful. What i need to do is select the 1st item from a combobox, update a textbox.text with the selected item, and pass the selected item to a function. Then wait for x seconds and start again, selecting the second item. I can get it to work in a single threaded application, but i need the interface to remain responsive. Any help greatly appreciated. EDIT: OK so changing the syntax worked for the example. However if i change it from Label1.CustomInvoke(Sub(l) l.text = "hello world!") (which worked just fine) to: Dim indexnumber As Integer = 0 ComboBox1.CustomInvoke(Sub(l) l.SelectedIndex = indexnumber) I get a cross threading error as though i didnt even use this method: Cross-thread operation not valid: Control 'ComboBox1' accessed from a thread other than the thread it was created on. So now im back to where i started? Any further help very much appreciated.

    Read the article

  • Getting JSON object from php authentication objective c

    - by iError
    I am trying to authenticate using the below code NSString *urlAsString =[NSString stringWithFormat:@"http://www.myurl.com/abc/authenticate.php"]; NSURL *url = [NSURL URLWithString:urlAsString]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest addValue:@"test" forHTTPHeaderField:@"m_username" ]; [urlRequest addValue:@"123" forHTTPHeaderField:@"m_password" ]; [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) { if ([data length] >0 && error == nil){ html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html); receivedData = [NSMutableData data]; } else if ([data length] == 0 && error == nil){ NSLog(@"Nothing was downloaded."); } else if (error != nil){ NSLog(@"Error happened = %@", error); } }]; // Start loading data NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data receivedData = [NSMutableData data]; } else { // Inform the user the connection failed. } My username password is correct, I think I am not making the proper call thats why I dont get the desired results and the web service is receiving the null parameters. What can be the issue? Any help appreciated.

    Read the article

  • Progressbar behaves strangely

    - by wanderameise
    I just created an application in C# that uses a thread which polls the UART for a receive event. If data is received an event is triggered in my main thread (GUI) and a progress bar is controlled via PerformStep() method (of course, I previously set the Max value accordingly). PerformStep is invoked using the following expression to handle cross threading this.Invoke((Action)delegate{progressBar2.PerformStep();}) When running this application the progressbar never hits its final value. It stops at 80%. When debugging and stopping at the line mentioned above, everything works fine using single steps. I have no idea what is going one! Start read thread on main thread: pThreadWrite = new Thread(new ThreadStart(ReadThread)); pThreadWrite.Start(); Read Thread: private void ReadThread() { while(1) { if (ReceiveEvent) { FlashProgressBar(); } } } Event that is triggered in main thread: private void FlashProgressBar() { this.Invoke((Action)delegate { progressBar2.PerformStep();}); } (It's a simplified representation of my code) It seems as if the internal progress is faster than the visual one.

    Read the article

  • Why Is the sender type null when dealing with events

    - by ChloeRadshaw
    From C# Via CLR: Note A lot of people wonder why the event pattern requires the sender parameter to always be of type Object After all, since the MailManager will be the only type raising an event with a NewMail EventArgs object, it makes more sense for the callback method to be prototyped like this: void MethodName(Mai l Manager sender, NewMail EventArgs e); The pattern requires the sender parameter to be of type Object mostly because of inheritance What if Mai lManager were used as a base class for SmtpMailManager? In this case, the callback method should have the sender parameter prototyped as SmtpMailManager instead of Mail Manager, but this can’t happen because SmtpMai lManager just inherited the NewMai l event So the code that was expecting SmtpMail Manager to raise the event must still have to cast the sender argument to SmtpMailManager In other words, the cast is still required, so the sender parameter might as well be typed as Obj ect The next reason for typing the sender parameter as Obj ect is just fexibility It allows the delegate to be used by multiple types that offer an event that passes a NewMail EventArgs object For example, a PopMai lManager class could use the delegate even if this class were not derived from Mail Manager I just simply cannot understand why the sender is an object - Why can it not be generified? so most of the time we do not need to do generic casts

    Read the article

  • List with non-null elements ends up containing null. A synchronization issue?

    - by Alix
    Hi. First of all, sorry about the title -- I couldn't figure out one that was short and clear enough. Here's the issue: I have a list List<MyClass> list to which I always add newly-created instances of MyClass, like this: list.Add(new MyClass()). I don't add elements any other way. However, then I iterate over the list with foreach and find that there are some null entries. That is, the following code: foreach (MyClass entry in list) if (entry == null) throw new Exception("null entry!"); will sometimes throw an exception. I should point out that the list.Add(new MyClass()) are performed from different threads running concurrently. The only thing I can think of to account for the null entries is the concurrent accesses. List<> isn't thread-safe, after all. Though I still find it strange that it ends up containing null entries, instead of just not offering any guarantees on ordering. Can you think of any other reason? Also, I don't care in which order the items are added, and I don't want the calling threads to block waiting to add their items. If synchronization is truly the issue, can you recommend a simple way to call the Add method asynchronously, i.e., create a delegate that takes care of that while my thread keeps running its code? I know I can create a delegate for Add and call BeginInvoke on it. Does that seem appropriate? Thanks.

    Read the article

  • Clear button at uisearchbar not working at all

    - by kevin.ng
    I created a search bar programmatically and added to my view using the codes below: - (void)viewDidLoad { searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(xPositionForSearchBar, yPositionForSearchBar, widthForSearchBar, heightForSearchBar)]; UIView *bg = [[searchBar subviews] objectAtIndex:0]; searchBar.delegate = self; searchBar.placeholder = @"Search record"; for(UIView *view in searchBar.subviews){ if([view isKindOfClass:[UITextField class]]){ UITextField *tf = (UITextField *)view; tf.delegate = self; break; } } [bg removeFromSuperview]; [self.view addSubview: searchBar]; } The code is implemented with UISearchBarDelegate and UITextFieldDelegate. I have tried using - (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar { NSLog(@"cancel clicked"); searchBar.text = @""; [aSearchBar resignFirstResponder]; } - (BOOL)textFieldShouldClear:(UITextField *)textField { NSLog(@"clear"); [self performSelector:@selector(searchBarCancelButtonClicked:) withObject:searchBar afterDelay: 0.1]; return YES; } and yet, the text inside the searchBar is not cleared at all when i click on the "clear button" - a circle with a "X" inside. The clear button works when I implemented it in IB. Wonder why? Kindly advice, many thanks.

    Read the article

  • WPF: issue updating UI from background thread

    - by Ted Shaffer
    My code launches a background thread. The background thread makes changes and wants the UI in the main thread to update. The code that launches the thread then waits looks something like: Thread fThread = new Thread(new ThreadStart(PerformSync)); fThread.IsBackground = true; fThread.Start(); fThread.Join(); MessageBox.Show("Synchronization complete"); When the background wants to update the UI, it sets a StatusMessage and calls the code below: static StatusMessage _statusMessage; public delegate void AddStatusDelegate(); private void AddStatus() { AddStatusDelegate methodForUIThread = delegate { _statusMessageList.Add(_statusMessage); }; this.Dispatcher.BeginInvoke(methodForUIThread, System.Windows.Threading.DispatcherPriority.Send); } _statusMessageList is an ObservableCollection that is the source for a ListBox. The AddStatus method is called but the code on the main thread never executes - that is, _statusMessage is not added to _statusMessageList while the thread is executing. However, once it is complete (fThread.Join() returns), all the stacked up calls on the main thread are executed. But, if I display a message box between the calls to fThread.Start() and fThread.Join(), then the status messages are updated properly. What do I need to change so that the code in the main thread executes (UI updates) while waiting for the thread to terminate? Thanks.

    Read the article

  • C#: Passing data to forms UI using BeginInvoke

    - by Bi
    Hi I am a C# newbie and have a class that needs to pass row information to a grid in the windows form. What is the best way to do it? I have put in some example code for better understanding. Thanks. public class GUIController { private My_Main myWindow; public GUIController( My_Main window ) { myWindow = window; } public void UpdateProducts( List<myProduct> newList ) { object[] row = new object[3]; foreach (myProduct product in newList) { row[0] = product.Name; row[1] = product.Status; row[2] = product.Day; //HOW DO I USE BeginInvoke HERE? } } } And the form class below: public class My_Main : Form { //HOW DO I GO ABOUT USING THIS DELEGATE? public delegate void ProductDelegate( string[] row ); public static My_Main theWindow = null; static void Main( ) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); theWindow = new My_Main(); Application.Run(theWindow); } private void My_Main_Load( object sender, EventArgs e ) { /// Create GUIController and pass the window object gui = new GUIController( this ); } public void PopulateGrid( string[] row ) { ProductsGrid.Rows.Add(row); ProductsGrid.Update(); } } Thanks!

    Read the article

  • issue with tab bar view displaying a compound view

    - by ambertch
    I created a tab bar application, and I make the first tab a table. So I create a tableView controller, and go about setting the class identity of the view controller for the first tab to my tableView controller. This works fine, and I see the contents of the table filling up the whole screen. However, this is not what I actually want in the end goal - I would like a compound window having multiple views: - the aforementioned table - a custom view with data in it So what I do is create a nib for this content (call it contentNib), change the tab's class from the tableView controller to a generic UIViewController, and set the nib of that tab to this new contentNib. In this new contentNib I drag on a tableView and set File's Owner to the TableViewController. I then link the dataSource and delegate to file's owner (which is TableViewController). Surprisingly this does not work and I receive the error: **Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x3b0f910'** This is bewildering to me since the file's owner is the TableViewController, which has been assigned to be both the dataSource and delegate. Does someone have either insight into my confusions, or a link to an example of how to have a compound view include a tableView? *update* I see this in the Apple TableView programming guide: "Note: You should use a UIViewController subclass rather than a subclass of UITableViewController to manage a table view if the view to be managed is composed of multiple subviews, one of which is a table view. The default behavior of the UITableViewController class is to make the table view fill the screen between the navigation bar and the tab bar (if either are present)." <----- I don't really get what this is telling me to do though... if someone can explain or point me to an example I'd be much appreciated!

    Read the article

  • Is there any seriously good reason why a view can not completely manage itself?

    - by mystify
    Example: I have an warning triangle icon, which is a UIImageView subclass. That warning is blended in with an animation, pulses for 3 seconds and then fades out. it always has a parent view! it's always only used this way: alloc, init, add as subview, kick off animation, when done:remove from superview So I want this: [WarningIcon warningAtPosition:CGPointMake(50.0f, 100.0f) parentView:self]; BANG! That's it. Call and forget. The view adds itself as subview to the parent, then does it's animations. And when done, it cuts itself off from the branch with [self removeFromSupeview];. Now some nerd a year ago told me: "Never cut yourself off from your own branch". In other words: A view should never ever remove itself from superview if it's no more referenced anywhere. I want to get it, really. WHY? Think about this: The hard way, I would do actually the exact same thing. Create an instance and hang me in as delegate, kick off the animation, and when the warning icon is done animating, it calls me back "hey man i'm done, get rid of me!" - so my delegate method is called with an pointer to that instance, and I do the exact same thing: [thatWarningIcon removeFromSuperview]; - BANG. Now I'd really love to know why this sucks. Life would be so easy.

    Read the article

  • How to avoid raising an event to a closed form?

    - by Steve Dignan
    I'm having trouble handling the scenario whereby an event is being raised to a closed form and was hoping to get some help. Scenario (see below code for reference): Form1 opens Form2 Form1 subscribes to an event on Form2 (let's call the event FormAction) Form1 is closed and Form2 remains open Form2 raises the FormAction event In Form1.form2_FormAction, why does this return a reference to Form1 but button1.Parent returns null? Shouldn't they both return the same reference? If we were to omit step 3, both this and button1.Parent return the same reference. Here's the code I'm using... Form1: public partial class Form1 : Form { public Form1 () { InitializeComponent(); } private void button1_Click ( object sender , EventArgs e ) { // Create instance of Form2 and subscribe to the FormAction event var form2 = new Form2(); form2.FormAction += form2_FormAction; form2.Show(); } private void form2_FormAction ( object o ) { // Always returns reference to Form1 var form = this; // If Form1 is open, button1.Parent is equal to form/this // If Form1 is closed, button1.Parent is null var parent = button1.Parent; } } Form2: public partial class Form2 : Form { public Form2 () { InitializeComponent(); } public delegate void FormActionHandler ( object o ); public event FormActionHandler FormAction = delegate { }; private void button1_Click ( object sender , EventArgs e ) { FormAction( "Button clicked." ); } } Ideally, I would like to avoid raising events to closed/disposed forms (which I'm not sure is possible) or find a clean way of handling this in the caller (in this case, Form1). Any help is appreciated.

    Read the article

< Previous Page | 32 33 34 35 36 37 38 39 40 41 42 43  | Next Page >