Hello I am developing one application as currency converter in that, I have URL it will return only one country currency but my module look like if user select one country then I need to display list of currency converter values of more than one country so I need call josn more than one times.
code is as:
responseData = [[NSMutableData data] retain];
ArrData = [NSMutableArray array];
NSString *strURL = [NSString stringWithFormat:#"http://rate-exchange.appspot.com/currency?from=%#&to=%#&q=1",strtablbase,strto];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
results = [responseString JSONValue];
livevalues=[responseString JSONValue];
With above code I am geting one country values but I need pass one strto values differently
Is it possible?
If yes, please give suggestions & help me out from this problem.
Yes you can use NSOperation Queues to call the different URL or if you are using Asihttprequest this Link may be useful for you :)
responseData = [[NSMutableData data] retain];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:#"country1"];
[array addObject:#"country2"];
for (NSString *urlString in array) {
strtablbase = [NSString stringWithFormat:#"%#",urlString];
NSString *strURL = [NSString stringWithFormat:#"http://rate-exchange.appspot.com/currency?from=%#&to=%#&q=1",strtablbase,strto];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Try this..
Of course it is possible to pass different values. Like you already did you can start connections one after another. If the server belongs to you, I would implement a request which returns me all the rates at a time. It saves the time for sending and receiving request. It really does not matter (for waiting time) if you get 100 bytes or 500 bytes in one request.
Otherwise you need to call many requests. Like said you can call one after another and even 2-3 requests at the same time. You can implement the mechanism your self or you can use NSOperationQueue which is made exactly for many requests by Apple.
For more information https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html
And I want yo point the method (of NSURLConnection)
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Related
I am building an iOS app in which I want to allow people to order stuff from stores that are registered in my database. To allow my users to see products, companies, etcetera, I need to download array's with the requested information. This is how I do that:
- (void)getOrderItems {
_dbAction = #"getOrderItems";
NSString *post = [NSString stringWithFormat:#"controller=%#&action=%#&orderNumber=%#", #"BakkerFunctions", #"getOrderItems", self.orderNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [NSURL URLWithString:#"http://www.mysite.nl/API/"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[request setURL:url];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSArray *orderItemsFromDatabase = [[NSArray alloc] init];
orderItemsFromDatabase = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:NULL][#"itemsFromDatabase"];
NSString *datastring = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%# Array:%#", datastring, orderItemsFromDatabase);
//convert array from database in array of custom objects
NSMutableArray *orderItems = [[NSMutableArray alloc] init];
for (int i = 0; i < orderItemsFromDatabase.count; i++) {
[orderItems addObject:
[[Item alloc] initWithItemName:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemName"]
itemDescription:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemDescription"]
itemCode:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemCode"]
itemBarCode:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemBarCode"]
itemPrice:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemPrice"]
itemQuantity:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemQuantity"]
itemUserRemark:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemUserRemark"]
itemCompany:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"itemCompany"]
productImageNumber:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"productImageNumber"]
category:[[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"category"]
itemImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.imagine-app.nl/ProductImages/%#%#", [[orderItemsFromDatabase objectAtIndex:i]objectForKey:#"productImageNumber"], #".jpg"]]]]]];
}
self.orderItems = [NSArray arrayWithArray:orderItems];
}
the getOrderItems method is a method inside the custom class I have for each order. when the user selects an orders, this method gets called to download the products that belong to this order. Now this process works all fine, but the problem is that the data gets receiver when my TableView already set itself up.
I want to add an observer to check if the amount of products in this array changes, and if it does, i want to update the tableview. I have searched for hours on SO an google, but not much is said about this and nothing useful to me.
any help would be much appreciated! thank you in advance
A simple solution would be to use a MBProgressHUD or a similar control which will display a message saying that please wait while the data is being downloaded. Once, the data is downloaded it will trigger a callback meaning that it has downloaded the data and then you can refresh your UITableView to reflect all the data.
Override the orderItems setter and reload the table in there.
- (void)setOrderItems:(NSArray*)items
{
_items = items;
[self.tableView reloadData];
}
I'm not adding an observer anymore, As soon as my custom class finished processing the received data, it calls the orders view controller. That made that the data is loaded before the tableview is set up and the problem is solved.
I would like to download an HTML documents(s) to parse the content. The server asks before entering this site to put in my user credentials. In Java I arrived with a basic authentication in an asynchronous task like this (JSoup):
String base64login = new String(Base64.encodeBase64(loginDaten.getBytes()));
Document parsableDoc = Jsoup.connect(myUrl).header("Authorization","Basic"+base64login)
.timeout(3000)
.get();
but in Objective-C it doesn't work so simple as I thought. Here I want to save the website in an NSData-Object or something similar (for example NSString). Got any ideas to solve this as simple as possible? (I'm such a pro in this sector as you can seeā¦)
You can do this using the NSURLConnection class ad NSMutableURLRequest. The idea is that you let the NSMutableURLRequest know what kind of auth method you want to use, and the credentials (login/password).
The following code should do it. (You will need the NSdata category for base64Encoding in this link http://cocoadev.com/wiki/BaseSixtyFour )
self.receivedData = [[NSMutableData alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"login",#"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self.receivedData length] >0)
NSString *result = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];
NSLog(#"The HTML String Is : %#", result);
{
iam developing one application.In that i want to use the google places api.I written the url and established the connection like
NSURL *URL = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=true&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
But in did finish loading delegate method i cant get the data.That code is here.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *parser = [[SBJSON alloc]init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:responseString error:nil];
}
So please tell me where i did the mistake.Why iam not getting the data.
Use ASIHTTPRequest framwork all these problems are automatically handle
all you have to do is just create a url
and parse the response using JSON framework
http://allseeing-i.com/ASIHTTPRequest/
According to my knowledge there are few mistaks.
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
The words responseData encoding are two world. I don't know whether you have pasted like that.
And I hope you have used -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegates to append data to responseData object.
I think you do not need to cast to NSDictionary. You can use following code.
NSString *content = [[NSString alloc] initWithBytes:[responseDate bytes] length:[responseDate length] encoding:NSUTF8StringEncoding];
NSLog(#"Data = %#", content);
NSError *error;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonD = [parser objectWithString:content error:&error];
I am doing a registration process with my app where the user enters in a number that I check against my db.. anyway long story short where I pass code into my NSString *startURL have a warning I cannot get rid of, it says
"Expression result unused"
have you ever experienced anything like this and if so how do I fix it?
-(void)startRegConnect:(NSString *)tempRegCode{
//tempRegCode = S.checkString;
NSLog(#"tempRegCode from RegConnection =%#",tempRegCode);
NSString *code = [[NSString alloc] initWithString:tempRegCode];
//urlstart string
NSString *startURL = (#"http://188.162.17.44:8777/ICService/?RegCode=%#",code); //warning here
NSURL *url = [NSURL URLWithString:startURL];
//create a request object with that url
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
//clear out the exisiting connection if there is on
if (connectionInProgress) {
[connectionInProgress cancel];
[connectionInProgress release];
}
//Instantiate the object to hold all incoming data
[cookieData release];
cookieData = [[NSMutableData alloc]init];
//create and initiate the connection - non-blocking
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
You can't just do (#"http://188.162.17.44:8777/ICService/?RegCode=%#",code). Use [NSString stringWithFormat:#"http://188.162.17.44:8777/ICService/?RegCode=%#", tempRegCode].
It's because of the parenthesis. By writing (blabla) it becomes an expression, which you are not using as an expressing, hence the compiler complains.
Change to [NSString stringWithFormat: ...]; and it becomes a method.
I have a NSURLConnection that gets data from a JSON web service, and everything works fine. I'm using it to post something to the server and get a success response.
After that call I want to initiate another NSURLConnection to refresh the data, so I'm doing so inside the connectionDidFinishLoading method, however this second connection isn't calling connectionDidFinishLoading when it is done loading.
Can I not initiate a NSURLConnection from inside the connectionDidFinishLoading method?
EDIT: Below is the code. I subclassed NSURLConnection to include a Tag NSString, calling the new class NSURLConnectionHelper. I'm using this to differentiate which connection has called the connectionDidFinishLoading.
- (void)connectionDidFinishLoading:(NSURLConnectionHelper *)connection
{
if([connection.Tag isEqual:#"NewMessage"]){
NSString *jsonString = [[NSString alloc] initWithData:receivedNewMessageData encoding:NSASCIIStringEncoding];
NSDictionary *results = [jsonString JSONValue];
[jsonString release];
[connection release];
if ([[results objectForKey:#"MessageAdded"] isEqual:#"True"]) {
User *newUser = [[User alloc] init];
[newUser retrieveFromUserDefaults];
if([newUser IsLoggedIn]){
Message *message = (Message *)[messages objectAtIndex: 0];
NSString *urlAsString = // url for webservice goes here
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnectionHelper *connection1 = [[NSURLConnectionHelper alloc] initWithRequest:request delegate:self];
connection1.Tag = #"GetLatestMessages";
[request release];
if (connection1) {
receivedLatestMessagesData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
}
}else if([connection.Tag isEqual:#"GetLatestMessages"]){
//do some other stuff but this code is never reached
}
}
I'm not familiar with NSURLConnectionHelper but it looks like you're never starting the connection.
I ended up having a space in my web service url, once I corrected that it worked.