How to convert NSData variable into NSInteger variable in iOS - ios

I have the following api method which returns NSData. I have called this method in another view controller. How to convert the NSData to NSInteger?
-(NSData *)getBusXMLAtStop:(NSString*)stopnumber
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString: [NSString stringWithFormat:#"http://www.google.com/ig/api?weather=,,,50500000,30500000",stopnumber]]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",dataReply);
return dataReply;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
api *ap = [[api alloc]init];
NSData *str = [ap getBusXMLAtStop:#"1"];
// Here is where I want to convert str into NSInteger type. How is this possible?
NSLog(#"this is success %#",ap.dataReply);
TWeatherParser *parser = [[TWeatherParser alloc]init];
[parser getInitialiseWithData:ap.dataReply];
[parser release];
[ap release];
}

Well, if you know that your data is really representing a single integer, the simplest way is the following:
NSData *data = ...;
int i;
[data getBytes: &i length: sizeof(i)];
UPD: NSInteger is defined depending on the architecture of the target processor and is either int or long. Feel free to replace int by NSInteger in the code above.
I'm also not sure that your data is an actual number and not it's string representation. In this case use something like
NSString *str = [[[NSString alloc] initWithData:data encoding:(encoding you need)] autorelease];
NSInteger value = [str intValue];

You can find a convenience initialiser on NSString called initWithData:. Please check out the documentation for more info.
EXAMPLE:
NSString * s = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];

Related

Objective - C stringByAddingPercentEncodingWithAllowedCharacters not working

I have a URL like so ANC & SHO.pdf
when I encode the URL like so:
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
now when I use this URL it does not work and I have a feeling it has to do with the & because when I tried another file, it worked perfectly I was able to load the PDF, but with the file with & I was not.
What Am I doing wrong?
Here is the output of escapedString
escapedString __NSCFString * #"Ancaster%5CANC%20&%20SHO%20-%20Laundry%20Closets%20to%20be%20Checked.pdf" 0x16ea33c0
I then use that to call a method:
NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:#"%#",escapedString]];
Here is the method:
-(NSArray *)GetPDFFileData:(NSString *)PDFFile
{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?PDFFile=%#",kIP,PDFFile];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return tableArray;
}
[NSCharacterSet URLHostAllowedCharacterSet] contains characters below:
!$&'()*+,-.0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~
which contains '&', so
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
won't escape '&' for you, then it's not URLEncoded.
see the question about how to url encode a string.

'initWithBase64Encoding' is deprecated?

I want to get the data from the string. i am using the following code but it seems to be deprecated.
NSData *data=[[NSData alloc]initWithBase64Encoding:(NSString *)dict];
I got the data. But its give me the warning that 'initWithBase64Encoding' is deprecated.
So is there any other method that will return data?
use this
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
instand of
NSData *data=[[NSData alloc]initWithBase64Encoding:(NSString *)dict];
Returns a data object initialized with the given Base-64 encoded string. (Deprecated in iOS 7.0. You should transition to either initWithBase64EncodedString:options: or initWithBase64EncodedData:options:.)
Use following
ENCODE
NSString *myString = #"Developer";
NSData *myData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [myData base64EncodedStringWithOptions:0];
NSLog(#"%#", base64String);
DECODE:
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedString);

Strange output when importing JSON to Objective-C

As the question says, I get an unexpected output when importing JSON into a TableView class.
JSON:
{"city":"Cambridge"}{"city":"Oxford"}
Objective-C:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.domain.com/cities.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", response);
Output:
<7b226369 7479223a 2243616d 62726964 6765227d 7b226369 7479223a 224f7866 6f726422 7d>
Fairly sure I'm structuring my JSON wrongly...
Your response is of NSData type and needs to be converted to a string.
NSString *responseString = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSUTF8StringEncoding];
NSLog(responseString);
You can also use the initWithData as described elsewhere
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
While this is useful for debugging, to actually extract or work with the data, you will want to convert it to dictionary or array.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];
From here, you can reference items in the dictionary.
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
NSLog(#"%#",responseArray);
NSMutableArray *cityArray =[[NSMutableArray alloc] init];
for (int i=0; i<[responseArray count]; i++)
{
[cityArray addObject:[NSString stringWithFormat:#"%#",[[responseArray objectAtIndex:i] valueForKey:#"city"];
}
Please note that, I believe you would fix that json and make it to json returning an array.
NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);

How to format string in IOS (#"url")

I am getting response from web service, the response is based on comma separated URl
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"ResponseData: %#", str);
And its output is like
ResponseData: http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg,http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg
I want to pass the response to my Images Gallery Which takes URL like below format
networkImages = [[NSArray alloc] initWithObjects:#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg",#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg",nil];
How can I format my response to #"URL",#"URL" so that I can store it into some variable e,g;abc and pass that to
networkImages = [[NSArray alloc] initWithObjects:abc,nil];
NSString has a method componentsSeparatedByString: which does exactly this.
networkImages = [str componentsSeparatedByString:#","];
I think you have two ways :
First way; (that i have already using in my news App)
* You must use JSON result.
* If you want you can use SBJsonParser and SDWebImage
NSError *myError = nil;
NSString *link = [NSString stringWithFormat:#"http://www.myexamplenews.com/mobil-app.php?q=imageList&id=%i",galleryId];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse *response=nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&myError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if (myError == nil)
{
NSArray *jsonGalleryDetail = [jsonParser objectWithString:jsonString];
jsonParser = nil;
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: jsonGalleryDetail];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
}
GalleryDetailView.h
#interface GalleryDetailView : UIView
{
}
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *)myList;
#end
GalleryDetailView.m
#implementation GalleryDetailView
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *) myList;
{
self = [super initWithFrame:frame];
if (self)
{
//Your code here
for (NSString *str in myList)
{
NSURL *imageURL = [NSURL URLWithString:str];
//This is SDWebImage extension.
UIImage *image = [UIImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
}
}
return self;
}
#end
Second way ;
NSArray *arr = [ResponseData componentsSeparatedByString:#","];
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: arr];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
I prefer to use JSON data. It is up to you. I hope this information will be helpful for you.

JSON parser returns Null

I am trying to learn how to parse JSON data so I can handle big databases. I wrote code to login into a website.
I have following JSON data from a successful login request:
JSON string : correct username and password [{"user_id":"7","first_name":"dada","last_name":"Kara","e_mail":"yaka#gmail","fullname":"Dada Kara","forum_username":"ycan"}]
and i use following code to parse but it doesnt parse it
-(IBAction)loginButton:(id)sender{
NSString *username = usernameTextfield.text;
NSString *password = passwordTextfield.text;
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:kPostUrl]];
[request setHTTPMethod:#"POST"];
NSString *post =[[NSString alloc] initWithFormat:#"e_mail=%#&password=%#", username, password];
[request setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseStr = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"Response : %#", responseStr);
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"JSON string : %#", json_string);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *name = [responseObj objectForKey:#"first_name"];
NSLog(#"Name : %#", name);
}
The result from my NSLog for name is NULL
Where is the problem and how can I parse such a data so when it comes to lots of rows I can save it to the local FMDB database on iphone
------------------------------EDIT---------------------------------------------------------------
Actual problem was response JSON string from server included echo beginning of the string,json parser only parses between double quotes "", so all i just needed to trim echo from string and parse new string.
and bingo!
//trim in coming echo
NSString *newString1 = [json_string stringByReplacingOccurrencesOfString:#"correct username and password\n" withString:#""];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:newString1 error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *userID = [dataDict objectForKey:#"user_id"];
NSLog(#"user_id: %#", userID);
output : user_id : 7
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:json_string error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *name = [dataDict objectForKey:#"first_name"];
Did you print recieve data ? is it showing recieve data from server ? If yes then try with different encoding.
You can use a tool like Objectify ($15 US) or JSON Accelerator ($0.99 US) in the Mac App store to automatically generate data models for you that would make the model as simple as doing object.firstName.

Resources