Objective C UITextField values blank - ios

I am trying to get the values from a few UITextFields I have added to my storyboard and send them as a JSON string to an API. I can hard code the values for the JSON string and everything works fine. Now I want to retrieve the values from the text fields and insert them in place of the hard coded values. The problem is that when I log the values to the console they are showing up as blank. I am not sure that I have the code correct to get the values from the ViewController to the method that sends the data. I followed several tutorials on how to get the data from the ViewController UITextFields. I connected the text fields to the properties in the ViewController.h file. I am hoping someone can help me figure out what I did wrong, hopefully I provided enough information.
I think the problem may be how I am trying to get the values from these lines of code in the timeMethods.m file:
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
NSString *name = controller.name.text;
NSString *type = controller.type.text;
NSString *date = controller.date.text;
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, retain) IBOutlet UITextField *name;
#property (nonatomic, retain) IBOutlet UITextField *type;
#property (nonatomic, retain) IBOutlet UITextField *date;
#end
ViewController.m
#import "ViewController.h"
#import "timeMethods.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize name;
#synthesize type;
#synthesize date;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendRequest:(id)sender {
[[timeMethods alloc] sendRequest];
}
- (IBAction)getRequest:(id)sender {
[[timeMethods alloc] getRequest];
}
#end
timeMethods.m
#import "timeMethods.h"
#implementation timeMethods
- (void)sendRequest {
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
NSString *name = controller.name.text;
NSString *type = controller.type.text;
NSString *date = controller.date.text;
NSURL *url = [NSURL URLWithString:#"http://throttle.com/my-rest-api/api/robots"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
name, #"name",
type, #"type",
date, #"year",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSString *strData = [[NSString alloc]initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"%#", strData);
}
- (void)getRequest {
NSString *serverAddress = #"http://throttle.com/my-rest-api/api/robots";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod:#"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSString *strData = [[NSString alloc]initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
#end
timeMethods.h
#import <Foundation/Foundation.h>
#interface timeMethods : NSObject
- (void)sendRequest;
- (void)getRequest;
#end

The trouble is that we've just allocated a brand new VC and asked for its UITextField's values here:
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
// controller.name is a brand new text field, created in the previous line
NSString *name = controller.name.text; // guaranteed to be #""
Of course this will be an empty text field. It was created in the previous line. Instead, get those values as params to your request from the view controller the user is using...
- (IBAction)sendRequest:(id)sender {
NSString *name = self.name.text;
NSString *type = self.type.text;
NSString *date = self.date.text;
[[timeMethods alloc] sendRequestWithName:name type:type date:date];
}
Naturally, add those parameters to the sendRequest method and remove the local vars.

Related

The correct way asynchronously call an object?

I have hobbled together one of my first objects. The goal of the object is to send a text message, which is does. However I'm calling it from the 2nd UIViewController within ViewDidLoad, and its still hanging within the Segue transition. So I know I need to get it asynchronously, but reading some other threads they implied that the proper way to go around it is to make it an "AppDelegate Object", so I would assume I would need to call the object from the AppDelegate, but I'm not really sure about how to go about that as I have not really worked with that in some tutorials I'm doing, and on top of that, is that the correct way to go about using my object?
initializing the object from my view controller
Twilio *twilio = [[Twilio alloc] init];
[twilio sendMessage: self.phoneNumber: [self getRandomNumberBetween:1000 to:9999]];
Header file
#import <Foundation/Foundation.h>
#interface Twilio : NSObject
#property (strong, nonatomic) NSString *TwilioSID;
#property (strong, nonatomic) NSString *TwilioSecret;
#property (strong, nonatomic) NSString *FromNumber;
#property (strong, nonatomic) NSString *ToNumber;
#property (strong, nonatomic) NSString *Message;
-(id)init;
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message;
#end
Implementation file
#import "Twilio.h"
#implementation Twilio
-(id)init {
self = [super init];
if(self) {
// Twilio Common constants
self.TwilioSID = #"A....3";
self.TwilioSecret = #"e...8";
self.FromNumber = #"5...2";
self.ToNumber = nil;
self.Message = nil;
}
return self;
}
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message
{
NSLog(#"Sending request.");
self.ToNumber = phoneNumber;
self.Message = message;
// Build request
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", self.TwilioSID, self.TwilioSecret, self.TwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
// Set up the body
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", self.FromNumber, self.ToNumber, self.Message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
return self.Message;
}
#end
Updated
With recommendation below I changed my object implementation like so:
//NSError *error;
//NSURLResponse *response;
//NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
NSLog(#"%#",response);
}];
Use method sendAsynchronousRequest:queue:completionHandler:
See it : https://stackoverflow.com/a/9270711/2828120

Setting Property Variables in Class Methods

Currently, I understand that I cannot set Property Variables within a class method.
For Example:
#ISUser.h
#interface ISUser : NSObject
#property (nonatomic, retain) NSString *username;
#property (nonatomic, retain) NSString *password;
#property (nonatomic, retain) NSString *email;
#property (nonatomic, retain) NSString *firstname;
#property (nonatomic, retain) NSString *lastname;
+ (void)logInWithUsernameInBackground:(NSString *)username
password:(NSString *)password
block:(ISUserResultBlock)block;
#end
I am looking through Parse's framework and am trying to get a better understanding of how to implement a login like they have done. The class method (void)logInWithUsernameInBackground:password:block is where I attempt to assign the property variables username and password but it's a no go.
Here is the implementation of the current method:
+ (void)logInWithUsernameInBackground:(NSString *)username password:(NSString *)password block:(ISUserResultBlock)block
{
//self.username = username // Of course, I cannot do this
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:#", "];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", kAPIHost, kAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%#, en-us;q=0.8", preferredLanguageCodes] forHTTPHeaderField:#"Accept-Language"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData * data = [[NSString stringWithFormat: #"command=login&username=%#&password=%#", username, password] dataUsingEncoding: NSUTF8StringEncoding];
[request setHTTPBody:data];
ConnectionBlock *connection = [[ConnectionBlock alloc] initWithRequest:request];
[connection executeRequestOnSuccess: ^(NSHTTPURLResponse *response, NSString *bodyString, NSError *error) {
block([self user], error);
} failure:^(NSHTTPURLResponse *response, NSString *bodyString, NSError *error) {
block([self user], error);
}];
}
Within the parse PFUser.h file, this is a class method... But how do they assign the property variables?
I know that static variables can be assigned/set within a class method but I would like to access such variables from another class.
EDIT: After viewing the first comment, The ISUser class has a singleton already implemented.
+ (instancetype)currentUser
{
static ISUser *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
But now what? I need to override the init method and set the variables? But how does the init method know what to set the variables to? Will I have to add parameters to the + (instancetype)currentUser like so + (instancetype)currentUser:username password:(NSString *)password then override the init method as well? + (instancetype)currentUser is another class method that I pulled from the PFUser framework.
You can not set properties in class method. You can do it on instance methods. Thats because properties are for instances of the class.
In the parse login method they use some properties as method parameters and use them for the login process, but not manipulate them.
Hope it helps

Issue : Convert an Object to json in iOS

I have one main entity class with name "Store" like :
Store.h :-
#import <Foundation/Foundation.h>
#import "SignIn.h"
#interface Store : NSObject
#property (nonatomic, retain) NSString *storeId;
#property (nonatomic, retain) NSString *storeProfileId;
#property (nonatomic, retain) NSString *storeName;
#property (nonatomic, retain) NSString *storeRegion;
#property (nonatomic, retain) SignIn *signIn;
#end
Store.m :-
#import "Store.h"
#implementation Store
#synthesize storeId, storeProfileId, storeName, storeRegion, signIn;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[Store alloc] init];
if (self != nil)
{
self.storeId = [coder decodeObjectForKey:#"storeId"];
self.storeProfileId = [coder decodeObjectForKey:#"storeProfileId"];
self.storeName = [coder decodeObjectForKey:#"storeName"];
self.storeRegion = [coder decodeObjectForKey:#"storeRegion"];
self.signIn = [coder decodeObjectForKey:#"signIn"];
}
return self;
}
- (void)encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:storeId forKey:#"storeId"];
[coder encodeObject:storeProfileId forKey:#"storeProfileId"];
[coder encodeObject:storeName forKey:#"storeName"];
[coder encodeObject:storeRegion forKey:#"storeRegion"];
[coder encodeObject:signIn forKey:#"signIn"];
}
#end
Here in Store class, i am taking one more class name "Sign In", that include some other attributes.
SignIn.h :-
#import <Foundation/Foundation.h>
#interface SignIn : NSObject
#property (nonatomic, retain) NSString *inTime;
#property (nonatomic, retain) NSString *outTime;
#property (nonatomic, retain) NSString *isStatus;
#end
SignIn.m :-
#import "SignIn.h"
#implementation SignIn
#synthesize inTime, outTime, isStatus;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[SignIn alloc] init];
if (self != nil)
{
self.inTime = [coder decodeObjectForKey:#"inTime"];
self.outTime = [coder decodeObjectForKey:#"outTime"];
self.isStatus = [coder decodeObjectForKey:#"isStatus"];
}
return self;
}
- (void)encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:inTime forKey:#"inTime"];
[coder encodeObject:outTime forKey:#"outTime"];
[coder encodeObject:isStatus forKey:#"isStatus"];
}
#end
Now i need to post this Store object on server. So I am creating dictionary using below code :
NSMutableArray *storeJSONArray=[NSMutableArray array];
for (Store *store in array1) {
NSMutableDictionary *storeJSON=[NSMutableDictionary dictionary];
[storeJSON setValue:store.storeId forKey:#"storeId"];
[storeJSON setValue:store.storeProfileId forKey:#"storeProfileId"];
[storeJSON setValue:store.storeName forKey:#"storeName"];
[storeJSON setValue:store.storeRegion forKey:#"storeRegion"];
//Sign In
[storeJSON setValue:store.signIn.inTime forKey:#"inTime"];
[storeJSON setValue:store.signIn.outTime forKey:#"outTime"];
[storeJSON setValue:store.signIn.isStatus forKey:#"isStatus"];
[storeJSONArray addObject:storeJSON];
}
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:storeJSONArray forKey:#"StoreRequest"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString =#"http://...................php";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
But i am not getting correct JSON, can you please check my code and let me know where is my mistake. Thanks in Advance.
If you are working on iOS 5+, then you can use NSJSONSerialization.
NSData *data= [NSJSONSerialization dataWithJSONObject:storeJSONArray
options:NSJSONWritingPrettyPrinted
error:nil];
if (data)
{
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON : %#",json );
}
You should serialize your NSMutableDictionary to JSON.
You can do this by using NSJSONSerialization:
NSError *error;
NSData *myData = [NSJSONSerialization dataWithJSONObject:storeJSON options:0 error:&error];
NSString *myJSON = [[NSString alloc] initWithBytes:[myData bytes]];
This should give you your JSON.
But i am not getting correct JSON, can you please check my code and let me know where is my mistake.
The problem is that you're not creating a JSON representation of the object anywhere; you're only creating a dictionary. Dictionaries can be converted to JSON (provided that they only contain certain types of data), but they're not JSON natively -- they're Objective-C objects. You probably want to add a call like:
NSError *error = nil;
NSData *json = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
You've shown us the NSCoding methods in your two classes, but you should understand that NSJSONSerialization doesn't rely on NSCoding, so none of that code is going to come into play.
Update: After modifying your example to include NSJSONSerialization, you say you're getting JSON that looks like this:
{"StoreRequest":[{"signOutStatus":false,"greetingStatus":false,"isBackFromVisit"‌​‌​:false,"digitalMerchandisingStatus":false,"feedbackStatus":false,"storeRegion":‌​"B‌​ishan Junction 8","isSubmit":false,"storeName":"Best Denki","storeId":"SG-2","planVisitStatus":false,"storeProfileId":5,"merchandisin‌​‌​gStatus":false}]}
That appears to be correct, given the values that you've added to dictionnary. But you say that what you want is:
{ "Checklist": [ { "vm_code": "SGVM0001", "store_id": "SG-12", "store_name": "Best Denki", "store_address": "Ngee Ann City", "visit_date": { "date": "2013-12-04 00:00:00", "timezone_type": 3, "timezone": "Asia/Calcutta" } "sign_in": { "date": "2013-12-05 11:03:00", "timezone_type": 3, "timezone": "Asia/Calcutta" }]
That doesn't at all match the object that you're passing to NSJSONSerialization. So, the problem here is that you're supplying incorrect data to NSJSONSerialization.
Try with
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:kNilOptions // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

Uploading large images using Base64 and JSON

I am using this function to upload an image to a server using JSON. In order to do so, I first convert the image to NSData and then to NSString using Base64. The method works fine when the image is not very large but when I try to upload a 2Mb image, it crashes.
The problem is that the server doesn't receive my image even though the didReceiveResponse method is called as well as the didReceiveData which returns (null). At first I thought it was a time out issue but even setting it to 1000.0 it still doesn't work. Any idea? Thanks for your time!
Here's my current code:
- (void) imageRequest {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myurltouploadimage.com/services/v1/upload.json"]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/design%i.png",docDir, designNum];
NSLog(#"%#",path);
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSArray *keys = [NSArray arrayWithObjects:#"design",nil];
NSArray *objects = [NSArray arrayWithObjects:imageString,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"Image uploaded");
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}
I finally decided to upload the Base64 image splitting it into smaller substrings. In order to do so, and as I needed many NSURLConnections, I created a subclass named TagConnection which gives a tag for each connection so that there's no possible confusion between them.
Then I created a TagConnection property in MyViewController with the purpose of accessing it from any function. As you can see, there's the -startAsyncLoad:withTag: function that allocs and inits the TagConnection and the -connection:didReceiveData: one which deletes it when I receive a response from the server.
Referring to the -uploadImage function, firstly, it converts the image into string and then splits it and put the chunks inside the JSON request. It is called until the variable offset is larger than the string length which means that all the chunks have been uploaded.
You can also prove that every chunk has been successfully uploaded by checking the server response every time and only calling the -uploadImage function when it returns success.
I hope this has been a useful answer. Thanks.
TagConnection.h
#interface TagConnection : NSURLConnection {
NSString *tag;
}
#property (strong, nonatomic) NSString *tag;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag;
#end
TagConnection.m
#import "TagConnection.h"
#implementation TagConnection
#synthesize tag;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag {
self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
if (self) {
self.tag = tag;
}
return self;
}
- (void)dealloc {
[tag release];
[super dealloc];
}
#end
MyViewController.h
#import "TagConnection.h"
#interface MyViewController : UIViewController
#property (strong, nonatomic) TagConnection *conn;
MyViewController.m
#import "MyViewController.h"
#interface MyViewController ()
#end
#synthesize conn;
bool stopSending = NO;
int chunkNum = 1;
int offset = 0;
- (IBAction) uploadImageButton:(id)sender {
[self uploadImage];
}
- (void) startAsyncLoad:(NSMutableURLRequest *)request withTag:(NSString *)tag {
self.conn = [[[TagConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag] autorelease];
}
- (void) uploadImage {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.mywebpage.com/upload.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1000.0];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/design%i.png", docDir, designNum];
NSLog(#"%#",path);
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSUInteger length = [imageString length];
NSUInteger chunkSize = 1000;
NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
NSString *chunk = [imageString substringWithRange:NSMakeRange(offset, thisChunkSize)];
offset += thisChunkSize;
NSArray *keys = [NSArray arrayWithObjects:#"design",#"design_id",#"fragment_id",nil];
NSArray *objects = [NSArray arrayWithObjects:chunk,#"design_id",[NSString stringWithFormat:#"%i", chunkNum],nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[self startAsyncLoad:request withTag:[NSString stringWithFormat:#"tag%i",chunkNum]];
if (offset > length) {
stopSending = YES;
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSError *error;
NSArray *responseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (!responseData) {
NSLog(#"Error parsing JSON: %#", error);
} else {
if (stopSending == NO) {
chunkNum++;
[self.conn cancel];
self.conn = nil;
[self uploadImage];
} else {
NSLog(#"---------Image sent---------");
}
}
}
#end
Please don't think this is the last option, this is just my observation.
I think you should send that NSData in chunks instead of complete Data.
I have seen such methodology in YouTube Video Uploading case.They send the Large set of NSData (NSData of Video File) in Chunks of many NSData.
They uses the Same Methodology for uploading the large data.
So should do google about the Youtube data Uploading API.And you should search out that method , YouTube Uploader Uses.
I hope it may help you .

flow of json to tableview

i have another problem this time, i'm fetching json codes that will be used to populate the tableview i have in my xib so, to start with my .h file
#interface FirstViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate> {
NSMutableArray *resultArray;
IBOutlet UITableView *thetableView;
NSMutableData *responseData;
}
#property (nonatomic,retain) NSArray *arrayTypes;
#property (nonatomic,retain) NSMutableArray *resultArray;
#property (nonatomic,retain) IBOutlet UITableView *thetableView;
in my .m file i implemented this
- (void) viewDidLoad{
responseData = [[NSMutableData data]retain];
NSURL *url = [NSURL URLWithString:#"http://localhost/fetch.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewDidLoad];
[self.thetableView reloadData];
}
in the connectiondidfinishloading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
}
and now the problem, the tableview has implemented both the numberofrowsinsection and didselectrowatindextpath methods but the latter is never called as the size of the array is 0 and even reloading, it doesn't work am i missing something or is there a similar tutorial to follow? sorry for the length just hoping the infos will be useful
you should reload tableview once you have the complete data..see the updated code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
//Reload your table with data..
[self.thetableView reloadData];
}

Resources