How can we pass multiple urls in collectionview - ios

I am creating a social networking application, in that am using Horizontal collection view cell displaying for post.
my requirements are,
I have 10 differnt url api but in that see (initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0" ) if i increase start_limit then i can get another post details.
I need to pass this data at the time of viewdidload
but how can get this post data at the time of viewdidload and collectionView numberOfItemsInSection how can i declare this suggest any ideas
if(indexPath.item==3)
{
NSString *post = [[NSString alloc] initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0"];
// NSLog(#"%# ",post);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:vblive/APIFiles/Services.php?"]]];
[request setHTTPMethod:#"POST"];
// NSLog(#"request is %#",request);
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
_myConnection2 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// NSLog(#"%#",conn);
if(_myConnection2)
{
NSLog(#"connction sucess");
}
else
{
NSLog(#"unsucess");
}
}
Thanks
Sravan

Try some thing like this
1. create a tag or you can use variable like
NSString *startLimitValue;
2. Then Assign the startLimit value in View did load or where ever you want like
startLimitValue=#"one"
3 then use indexPath to assign Start limit value to different collection view cell
You can use Tags for specific item also
then dynamically set the no of items using Count method
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if(check your condtion)
{
return [yourObject count];
}
else
if(check your conditon)
{
return [yourObject count];
}
}

I guess start limit has the integer value.
I would suggest for each view give the tag in collection view as 0 or 1 or 2....as the start limit values.
Then when user tap on item then using initWithFormat format the string using tag value of the item.

Related

how to POST UIPickerview Value to JSON url

I have two UITextFields(cityNames,collageNames).I get data for JSON url.I get and Placed data to UIPickerview based on UITextFields. when select cityName that city name placed into UITextFields but now I need that particular index value post to JSON URL and same as collage name
. I know about String value Post to JSON url. But I don't know about How to post UIPickerview Index Value to JSON url.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(#"select row is %d",row);
if(pickerView.tag==1){
CityName.text = [secondArray objectAtIndex:row];
string1=
[NSString stringWithFormat:#"%d",[yourpicker selectedRowInComponent:0]];
NSLog(#"string ring %#",string1);
}
else if(pickerView.tag==2){
CollageName.text = [firstArray objectAtIndex:row];
string2=
[NSString stringWithFormat:#"%d",[yourpicker selectedRowInComponent:0]];
}
}
String1 and String2 is get IndexValue .But i don't how to pass that particular Stringvalue to JSON.I tired but When i Print String 1 and 2 using NSLog outSide of Did-select Method it's showing null Values.When i Print String values in Didselect method it's showing select Index value
NSString *post =[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",cityname.text,collagename.text];
or
NSString *post =[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",string1,string2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.3.35:8090/SaveDollar/rest/users/add"]]];
NSLog(#"getData%#",request);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSLog(#"getData%#",request);
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{ webData3=[NSMutableData data];
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
I tired like this (above code).i not getting.So Please give me any idea about How to post UIPickerView indexValue to JSON Url.
Thanks in Advanced .
You have two different pickerViews so no issue.
Get the actual values from two different arrays as:
NSString *collegeName=[collegeArray objectAtIndex:[self.dataPicker1 selectedRowInComponent:0]];
OR:
If you are able to see textField values, you can use them also as:
NSString *collegeName=collegeTextField.text;
One more way to get index i.e. from textField:
int index=[collegeNameArray indexOfObject:collegeName];
then you can pass index to your urlString.
To get the pickerView selected index use:
[self.dataPicker1 selectedRowInComponent:0]
You can build a urlString as:
urlString=[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",[self.dataPicker1 selectedRowInComponent:0],[self.dataPicker2 selectedRowInComponent:0]];

Trouble posting to database, from iOS app

I'm having a problem updating my database from an iOS app...
Sql statements
<?php
// Create connection
$con=mysqli_connect("server_name","user_name","user_code","table_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'table.name'
$sql = "SELECT * table_name";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
$sql = "INSERT INTO table_name (column_name) VALUES('1')";
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
My iOS code
for (Tickets *items in _feedItems){
if ([resultText.text isEqual:(id) items.ticketNumber]) {
status.text = #"Match found";
//Contacting database------------------------------
NSString *strURL = [NSString stringWithFormat:#"TicketDate=%#", items.ticketDate];
NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://webservice.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-
Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
//Contacting database END-------------------------------------------
break;
}else {
status.text = #"Match not found";
}
}
I get a Connection Succesful from the NSLog but there is nothing getting updated in my database.
I'm trying to manually type in a ticket number with an app, and if that matches with a ticket in the database (it works), then I want the the ticketDate to change from 0 to 1.
But it does not change :/
You are not calling
[conn start];
to have your request effectively sent. I.e.:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
You should also be aware that the request will be sent asynchronously, this means that you will not get the response right after calling start. What you should do, if you want to stay with an async connection, is implement a data delegate, and at least its – connection:didReceiveData:, – connectionDidFinishLoading:, and connection:didFailLoadingWithError: methods.
Alternatively, you might consider sending the request synchronously, i.e., just replacing
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
with:
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
But this kind os request will block your app UI, unless you send them on a background thread.
In the database I have a row with a ticketNumber and ticketDate. If the number typed into my app is the same as a ticketNumber in my database, then i want the same row's ticketDate to change from 0 to 1.

How to use a single connection to the network in several classes

Guys help deal with a problem I'm new to programming, and accordingly I have a problem in general, I do not know how to work with the network! I wrote a class in which I log into the site after login I can not use the connection to send other requests in other views!!!
here's what I wrote:
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtUserName text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Пожалуйста заполните все поля!!!" :#"Авторизация не удолась!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[txtUserName text],[txtPassword text]];
NSURL *url=[NSURL URLWithString:#"http://chgu.org/?mobile=1"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
if([jsonObject objectForKey:#"error"])
{
[self alertStatus:#"Ошибка ввода данных" :#"Ю хав а трабл"];
} else {
[self alertStatus:#"Авторизация прошла успешно" :#""];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
}
how do I use this connection when I move to a different view!
Please tell me anything all night sitting at the computer can not figure out
You have the right idea, assuming that you want relatively tight coupling between these controllers via that delegate protocol.
Since neither controller knows about the other until that delegate property is set you need to have some object which has a reference to both of them wire up that relationship. In your case that's probably the application delegate which can create both controllers, set one as the delegate of the other, and pass both along to your tab bar controller.
What you might actually want is to have the app delegate give both controllers a reference to some shared model object. Your FirstViewController can update that model when you tap a button and your SecondViewController can observe changes to the model to update it's display (or just update its view when it appears based on the current model state). That way your controllers don't need to know anything about each other.
in secondVC, define something like the following:
#protocol secondVCDelegate
#interface secondVC : UIViewController
#property (nonatomic, assign) id<secondVCDelegate> delegate;
#end
#optional
-(void)someDelegateMethod:(secondVC*)viewController;
#end
at the time of creating the instance of secondVC you must assign the delegate property of secondVC to self! something like this:
// in firstVC
secondVC vc = [[secondVC alloc]...];
vc.delegate = self;
[navcontroller pushVC:vc];
the line vc.delegate = self; does the trick.
hope it helps...

IOS Creating Utility Class For NSURL

I have a project I am working on that has a number of different news feeds and announcement boards that displays post from various sources. Currently I have the code for the like, delete and flag buttons in methods contained in each class file for the views that display the feeds. I have been trying to craft a utility class that allows me to place the code for the three functionalities listed above in one object to be used throughout the project. I have done the exact same type of thing in C++ or Java, but am having issues reproducing it in objective-c. The like, delete and flag buttons use the NSURL libraries to interact with the web service. Bellow is an example of one of the methods I am trying to implement in the utility class, and is the code used to be implemented in the like buttons:
+ (void)btnLikeAction:(UIButton *)btnLike userIdString:(NSString *)userId contentSource:(NSString *)sourceId cellUsed:(NewsfeedCell *)cell dataForCell:(Post *)post
{
BOOL hasLiked = post.hasLiked;
UILabel *likeLabel = cell.likeCount;
NSString *pId = post.postId;
if (hasLiked)
{
[btnLike setEnabled:NO];
NSString *url = [NSString stringWithFormat: #"http://192.155.94.183/api/v1/likes/unlike/%#/%#/%#/", sourceId, pId, userId];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount--;
likeLabel.text = [NSString stringWithFormat:#"%i", localCount];
post.likeCount = [NSString stringWithFormat:#"%i", localCount];
post.hasLiked = NO;
[btnLike setEnabled:YES];
}
else
{
[btnLike setEnabled:NO];
NSError *err = nil;
NSDictionary *likeData = [NSDictionary dictionaryWithObjectsAndKeys:
userId, #"user_id",
pId, #"source_id",
sourceId, #"source",
nil];
NSData *JSONLike = [NSJSONSerialization dataWithJSONObject:likeData options:NSJSONWritingPrettyPrinted error:&err];
NSString *url = #"http://192.155.94.183/api/v1/likes.json";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [JSONLike length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:JSONLike];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount++;
likeLabel.text = [NSString stringWithFormat:#"%i", localCount];
post.likeCount = [NSString stringWithFormat:#"%i", localCount];
post.hasLiked = YES;
[btnLike setEnabled:YES];
}
}
This code uses a web service to update the number of likes for a specific piece of content. It works when the method is placed into the individual ViewController class files, but when I try to make a utility class with the individual methods I run into issues with the didReceiveAuthenticationChallenge, didReceiveResponse, didReceiveData and connectionDidFinishLoading methods not being called. Originally, I assumed that the delegate methods would be called in the file that that the utility methods were called in. But that was not the case. When I implemented the method definitions in the actual utility class, the methods still weren't called. I did some research on the topic and looked into this article but found I was unable to find substantial resources that helped my specific situation. How do I set up my utility class? I can post the full code of the utility if needed.
As #serrrgi already said, the problem is that btnLikeAction:... is a class method, so that self is the class itself. You have the following options:
Make all delegate methods class methods, e.g.
+ (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
}
Create an instance of your Utility class and use that as delegate:
YourClass *u = [[self alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:u];
Use sendAsynchronousRequest:..., which does not need a delegate:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data != nil) {
NSLog(#"success");
} else {
NSLog(#"error: %#", error);
}
}];

iOS: using async

I currently have a screen with 2 tables. I'm getting the data synchronously and putting it on the screen. Code looks something like:
viewController.m
DBAccess_Error_T = [getList:a byCompanyID:1];
DBAccess_Error_T = [getList:b byCompanyID:2];
[self putListAOnScreen];
[self putListBOnScreen];
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
// Pack this up in JSON form
[self queryDB:postData];
// Unpack and put it into variable a
}
+ (id)queryDB:(id)post
{
// Send request
// Get back data
}
I'm now trying to switch this over to async and I'm struggling. It's been hard even with website tutorials and documentations.
Since all of my database utilities are in separate files from the viewControllers, I'm not sure how I can use the didReceiveData and didReceiveResponse handlers. Also, since I have 2 arrays to fill for my 2 tables, how do I distinguish the difference in didReceiveData?
Instead, what I'm trying to do now is use sendAsynchronousRequest, but it seems I need to create an unpack function for every send function...let me know if I'm way off here...it looks something like:
viewController.m stays the same
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
NSDictionary *post = /*blah blah*/
[self queryDB:post output:(a)];
}
+ (id)queryDB:(id)post output:(id)output
{
NSError *error;
NSData *jsonPayload = [NSJSONSerialization dataWithJSONObject:post options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:jsonPayload];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
if ([data length] >0 && error == nil)
{
[self unpackDataForList:output data:data]; // This function needs to be different depending on which function called queryDB...the data will be unpacked in a different way
}
}
}
+ (void)unpackDataForList:(id)output data:(NSData*)data
{
// Do my unpacking here and stick it into 'output'.
}
How can I call a different unpackData function? are function pointers the right way to do this? Is this approach way off? Any tips would be greatly appreciated!
Have you ever looked at ASIHTTPRequest? It makes your life a lot easier by allowing you to use blocks. Here's an example of how to make an asynchronous request:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
}
You can find more information here:
http://allseeing-i.com/ASIHTTPRequest/

Resources