wait for request ends before execute tableview init - objective-c

following code uses ASIhttprequest to fill appData array. View also includes a tableview and when is launched, getData function is executed first but then I would like to wait until request ends and appData is filled before execute tableView init methods. Now tableView methods are executed before request ends. How to do that? Thank you.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
NSArray *datos = [[NSArray alloc] initWithObjects:(#"test"), nil];
self.appData = datos;
[datos release];
}
[self getData];
return self;
}
- (void)getData
{
activityIndicator.hidden = NO;
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:#"http://test.com/iphone.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSLog(#"URL = %#",url);
[request setValidatesSecureCertificate:NO];
[request setRequestMethod:#"POST"];
[request setPostValue:#"admin" forKey:#"key1"];
[request setPostValue:#"admin" forKey:#"key1"];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"%#", [request responseString]);
//NSLog(#"Response %d ==> %#", request.responseStatusCode, [request responseString]);
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
appData = [[request responseString] componentsSeparatedByString: #"#"];
int x =0;
while (x<[appData count] - 1)
{
NSLog(#"cells = %#",[appData objectAtIndex: x]);
x = x+1;
}
}

You have two options here:
you alloc and init your tableview AFTER the request did finished - this is not possible if you used IB to create your tableview
you return 0 in your UITableViewDelegates - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section method until the request is not finished. Then, reload the table and return the actual record count.

Related

Get website console log message through objective c

Using ObjectiveC I had developed the browser like this
- (void)setupWebView {
self.webView = [[WKWebView alloc] initWithFrame: CGRectZero];
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
self.webView.allowsBackForwardNavigationGestures = YES;
[self.baseView addSubview: self.webView];
[self setupWKWebViewConstain: self.webView];
}
- (void)setURL:(NSString *)requestURLString {
NSURL *url = [[NSURL alloc] initWithString: requestURLString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 5];
[self.webView loadRequest: request];
}
#pragma mark - WKScriptMessageHandler Methods
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(#"log: %#", message.name);
}
In my website I had given
console.log("Hello world!");
This console value will keep changing, I want to get those values through ObjectiveC, I tried didReceiveScriptMessage but it is not working.
Is there any other way to get console.log values through Objective C

Can only receive <5b5d> as a response from NSURL query.. Xcode

I'm trying to receive a correct response from a NSURL POST request in Objective-C.
My script uses PHP to send tyre sizes (4 parameters) which the user has inputted using textfields, (and then presses Submit - IB Action Button1), and then the idea is to output
the response (Quantity in stock) via the self.instock.text label.
However, ResponseData is only showing up on the console as <5b5d>.
I have already inserted rows in the MySQL database to match the test data from the App, so that's not the problem.
Can anyone see why I only receive this response?
Many, many thanks in advance!!
#import "GetQuoteViewController.h"
#interface GetQuoteViewController ()
#end
#implementation GetQuoteViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(#"You entered %#",self.tyrewidth.text);
[self.tyrewidth resignFirstResponder];
NSLog(#"You entered %#",self.tyreprofile.text);
[self.tyreprofile resignFirstResponder];
NSLog(#"You entered %#",self.wheelsize.text);
[self.wheelsize resignFirstResponder];
NSLog(#"You entered %#",self.speedrating.text);
[self.speedrating resignFirstResponder];
return YES;
}
- (IBAction)Button1:(id)sender {
NSString *meme = _tyrewidth.text;
NSString *meme1 = _tyreprofile.text;
NSString *meme2 = _wheelsize.text;
NSString *meme3 = _speedrating.text;
_displayMeme.text = [NSString stringWithFormat:#"%# %# %# %#",meme,meme1,meme2,meme3];
NSString *rawStr = [NSString stringWithFormat:#"tyrewidth=%#&tyreprofile=%#&wheelsize=%#&speedrating=%#", _tyrewidth.text, _tyreprofile.text, _wheelsize.text, _speedrating.text];
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://budget-tyresofhull.com/service2.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *name = responseString;
self.instock.text = name;
}
#end

NSURLConnection delegates not being called even when run on main thread

I know that this kind of question has been asked many times, but all of them point to saying that the connection must be on a different thread.
-(void)distanceMatrix{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:distanceMatrixURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
connection2 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection2 scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
NSLog(#"Is%# main thread", ([NSThread isMainThread] ? #"" : #" NOT"));
[connection2 start];
if (connection2)
{
responseData2 = [NSMutableData data];
connectionIsActive = YES;
} else {
NSLog(#"connection failed");
}
}
- (void)connection2:(NSURLConnection *)connection2 didReceiveResponse:(NSURLResponse *)response
{NSLog(#"recieved response");
[responseData2 setLength:0];
}
- (void)connection2:(NSURLConnection *)connection2 didReceiveData:(NSData *)data
{
[responseData2 appendData:data];
}
- (void)connection2:(NSURLConnection *)connection2 didFailWithError:(NSError *)error
{
connectionIsActive = NO;
NSLog(#"failed!!");
}
- (void)connection2DidFinishLoading:(NSURLConnection *)conn
{
connectionIsActive = NO;
SBJsonParser *json = [[SBJsonParser alloc] init];
NSString *responseString = [[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary *parsedJSON = [json objectWithString:responseString error:&jsonError];
travelTime= [[[[parsedJSON valueForKey:#"rows"] valueForKey:#"elements"] valueForKey:#"duration"] valueForKey:#"text"];
NSLog(#"traveltime = %#", travelTime);
}
When I log it, it says that it runs on the main thread. Connection2 is active but none of the delegates are called.
Also, this is the way I am calling distanceMatrix method
-(id)initWithJsonResultDict:(NSDictionary *)jsonResultDict andUserCoordinates: (CLLocationCoordinate2D)userCoords andTimeURL:(NSString*)timeURL
{
self.distanceMatrixURL = timeURL;
[self distanceMatrix];
//more code here for other purposes
}
Because you have added a 2 into the names of all of the delegate methods. That changes the method signature so you aren't implementing the correct methods. Remove all of the 2 at the start of the methods - (void)connection2: and it should work.

iOS Get Connection

This is my first time on this site and I am very new to coding so I was wondering if somebody could help me out.
I want to set a get request from my iphone app to my website and get the information echoed back from the website to my phone.
I have gotten this far but do not know where to go from here. Any help would be much appreciated, thanks!
- (void)myData:(id)sender
{
NSString *DataToBeSent;
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
[receivedData release];
receivedData = [[NSMutableData alloc] init];
DataToBeSent = [[NSString alloc] initWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%#",sender];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
[dataToBeSent release];
}
OLD WAY
- (void)myData:(id)sender
{
NSString *dataToBeSent;
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
[receivedData release];
receivedData= [[NSMutableData alloc] init];
dataToBeSent= [[NSString alloc] initWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];
Theconn= [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog (#"test1 %#", theRequest);
NSLog (#"test2 %#", Theconn);
[dataToBeSent release];
}
Then the following methods are called and I get my data BUT if I sent another request after my first one but different data on the same connection, it would always give me the same result which shouldn't happen
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[self displayAlertCode:stringData];
[stringData release];
// Do unbelievably cool stuff here //
}
Assuming your data loaded properly you can convert the data into a string and do whatever you want with it.
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
//Make sure to set the correct encoding
NSString* responseString = [[NSString alloc] initWithData:response1 encoding:NSASCIIStringEncoding];
If your server returns JSON there are 3rd party libraries that can parse the string into collections like NSArray and NSDictionary. If your server returns XML then NSXMLParser could be something you can use.
EDIT
I've changed your code to manage the memory a little differently.
.h
#property (nonatomic,retain) NSMutableData * receivedData;
#property (nonatomic,retain) NSURLConnection * Theconn;
.m
#synthesize receivedData;
#synthesize Theconn;
//A bunch of cool stuff
- (void)myData:(id)sender
{
//If you already have a connection running stop the existing one
if(self.Theconn != nil){
[self.Theconn cancel];
}
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
//This will release your old receivedData and give you a new one
self.receivedData = [[[NSMutableData alloc] init] autorelease];
NSString *dataToBeSent = [NSString stringWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php? Data=%#",sender];
NSURLRequest *theRequest= [NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];
//This will release your old NSURLConnection and give you a new one
self.Theconn = [NSURLConnection connectionWithRequest:theRequest delegate:self];
NSLog (#"test1 %#", theRequest);
NSLog (#"test2 %#", Theconn);
}
//...
//Your delegate methods
//...
- (void) dealloc{
[receivedData release];
[Theconn release];
[super dealloc];
}

What is asynchronous image downloading and how can I download too many images?

I have too many images to be download from net into iPhone? How can I build an application using asynchronous image downloading?.
Most common and simple way is to use NSURLConnection with asynchronous request. Create connection with request set delegate, and it starts load data in background calling delegate methods when receive next chunk of data, finish load or fail. when first object is loaded, start next and so on.
Here is slightly simplified working code:
- (id)init...{
//...
requestData = [[NSMutableData alloc] initWithCapacity:1000000];
myImages = [[NSMutableArray alloc] initWithCapacity:100];
myImagesAddresses = [[NSMutableArray alloc] initWithCapacity:100];
[myImagesAddresses addObject:#"http://mysite.com/image1"];
[myImagesAddresses addObject:#"http://mysite.com/image2"];
//...
[self loadNextImage];
//...
}
-(void)loadNextImage{
if ([myImagesAddresses count]){
NSURL * imageURL = [NSURL URLWithString:[myImagesAddresses lastObject]];
NSURLRequest * myRequest = [NSURLRequest requestWithURL:imageURL];
[[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
NSLog(#"start load URL:%#", imageURL);
}
else{
NSLog(#"No more images to load");
// all images are ready to use!
}
}
// connection delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{
NSLog(#"more data...");
[requestData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)inConnection{
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:requestData]]];
[inConnection release];
inConnection = nil;
NSLog(#"Image from:%# loaded",[myImagesAddresses lastObject]);
[myImagesAddresses removeLastObject];
[self loadNextImage];
}
- (void)connection:(NSURLConnection *) inConnection didFailWithError:(NSError *)error{
[inConnection release];
inConnection = nil;
NSLog(#"Image from:%# not loaded",[myImagesAddresses lastObject]);
[myImagesAddresses removeLastObject];
[self loadNextImage];
}