Custom Type FrameWork in ios - ios

I have created one Custom type Frame work, and that frame work i added in to my app, in that custom frame work i added simple method, that will return the normal string, But my question is i want to use that framework as a API calls like login and registration and all, i used NSJSONSERIALIZATION for fetch data from json, it will return the values, but i want to use that data in my app, can any one tell me , i am very new in custom type Frameworks and all;
-(void )JsonData :(NSDictionary *)dictionary method:(NSString *)method url:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:method];
NSLog(#"apiCall RequestUrl: %#, HTTPMethod: %#, RequestData: %#", request.URL.absoluteString, method, dictionary);
if ([method isEqualToString:#"POST"] || [method isEqualToString:#"PUT"])
{
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:(NSDictionary *)dictionary options:0 error:nil];
[request setHTTPBody:dataToSend];
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *responseError)
{
NSDictionary *responseData;
if (responseError)
{
responseData = [NSDictionary dictionaryWithObjectsAndKeys:
#"Error", #"status",
responseError.localizedDescription, #"message",
nil];
}
else if ([(NSHTTPURLResponse *)response statusCode] != 200)
{
responseData = [NSDictionary dictionaryWithObjectsAndKeys:
#"Error", #"status",
#"Invalid Response from server.", #"message",
nil];
}
else if ([[Response getCustomStatus:(NSHTTPURLResponse *)response] isEqualToString:#"invalid_session"])
{
responseData = [NSDictionary dictionaryWithObjectsAndKeys:
#"Error", #"status",
#"Your session has been expired.", #"message",
nil];
}
else
{
responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&responseError];
}
NSLog(#"apiCall ResponseData: %#", responseData);
CustomerInfo *customer = [[CustomerInfo alloc]init];
customer.session = [[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"session"];
NSLog(#"JsonData:%#",[[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"session"]);
NSLog(#"Data:%#",customer.session);
customer.groupID = [[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"group_id"];
NSLog(#"%#",[[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"group_id"]);
NSLog(#"Data:%#", customer.groupID );
customer.cutomerID = [[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"customer_id"];
NSLog(#"%#",[[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"customer_id"]);
NSLog(#"Data:%#", customer.cutomerID );
customer.stylistProfilepicUrl = [[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"stylist_profile_url"];
NSLog(#"%#",[[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"stylist_profile_url"]);
NSLog(#"Data:%#", customer.stylistProfilepicUrl);
customer.fbUserID = [[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"fb_user_id"];
NSLog(#"%#",[[[responseData objectForKey:#"data"]objectAtIndex:0]objectForKey:#"fb_user_id"]);
NSLog(#"Data:%#", customer.fbUserID );
}];
}
This is my Frame Work code,
in my app i jsut call this code and send the parameters,
i got the response,but while i am printing the data, it showing null values in my app,
Can any one suggest me or send me any link or tutorial

If you are getting valid data, then log
NSLog(#"apiCall ResponseData: %#", responseData.description);
Check and try to print any error.description probably in the last else part

Related

the arabic string is not readable when load json

Code:
+(id)loadJSONDataFromURL:(NSString *)urlString{
MsgsHelper *msg=[[MsgsHelper alloc]init];
// This function takes the URL of a web service, calls it, and either returns "nil", or a NSDictionary,
// describing the JSON data that was returned.
NSError *error;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Call the web service, and (if it's successful) store the raw data that it returns
NSURLResponse *response = nil; //
NSData *data = [ NSURLConnection sendSynchronousRequest:request returningResponse: &response error:&error ];
//here we get the respond from NSURLResponse and then we check for the statusCode //1
//200 is ok,, 0 is no internet connection else is server error //2
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;//1
//any warning like this one with integers shuold add the casting (int)
int statCode = (int)[httpResponse statusCode];//2
if(statCode == 200){
if (!data)
{
//NSLog(#"Download Error: %#", error.localizedDescription);
return nil;
}
// Parse the (binary) JSON data from the web service into an NSDictionary object
id dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (dictionary == nil) {
//NSLog(#"JSON Error: %#", error);
return nil;
}
return dictionary;
}else if(statCode == 0){
[msg alertStatus:NSLocalizedString(#"No internet", #"Message") :#"" :0 ];
return nil;
}else{
//Server Error
//NSLog(#"Server Error");
[msg alertStatus:NSLocalizedString(#"Server Error", #"Message") :#"" :0 ];
return nil;
}}
the problem on result as below:
results: (
{
"Name" = "\U0633\U0639\U0648\U062f \U0639\U0628\U062f\U0627\U0644\U0639\U0632\U064a\U0632 \U064a\U0646 \U062c\U062f\U064a\U062f";
"location" = CENTER;
}
)
maybe need to dataUsingEncoding to read arabic string, but how do it.
Thanks,

ios send push notification with GCM Device to Device

I want to be able to send push notification to a topic from device to device. I am already able to receive the notifications if I send them from a server but in the end I don't want a server to interact with my apps.
I wrote a method that send the notification that look like this :
-(void)sendNotif {
NSDictionary *message = #{
#"notification" : #"{ \"text\" : \"test\", \"title\" : \"test\"}",
#"to" : #"/topics/test"
};
// kSenderID is the senderID you want to send the message to
NSString *kSenderID = #"X";
NSString *to = [NSString stringWithFormat:#"%##gcm.googleapis.com", kSenderID];
DLOG(#"dict %#, to : %#",message, to);
[[GCMService sharedInstance] sendMessage:message to:to withId:#"id1"];
}
But it seems nothing is sent.
So I have 2 questions :
How do I write my method?
How do I implement the callback methods?
A solution I found is to create my own HTTPRequest like in google example :
-(void)sendNotif {
NSString *sendUrl = #"https://android.googleapis.com/gcm/send";
NSString *subscriptionTopic = #"/topics/test";
NSString *title = notifTitle.text;
NSString *body = notifBody.text;
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sendUrl ]];
req.HTTPMethod = #"POST";
[req setValue:#"application/json" forHTTPHeaderField: #"Content-Type"];
[req setValue:#"key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" forHTTPHeaderField: #"Authorization"];
NSDictionary *message = [self getMessageTo:subscriptionTopic withTitle:title withBody:body];
NSError *jsonError;
NSMutableString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message options:NSJSONWritingPrettyPrinted error:&jsonError];
if (! jsonData) {
NSLog(#"Got an error: %#", jsonError);
} else {
jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
DLOG(#"json string%#", jsonString);
req.HTTPBody = jsonData;
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error != nil) {
DLOG(#"truc error %#",error);
} else {
DLOG(#"Success! Response from the GCM server:");
DLOG(#"%#",response);
}
}];
}
-(NSDictionary *) getMessageTo:(NSString *) to withTitle:(NSString *) title withBody:(NSString *) body{
// [START notification_format]
NSDictionary *message = #{
#"notification" : #{#"title" : title,#"text" : body},
#"to" : to
};
return message;
// [END notification_format]
}
There is no normal way to publish a message to topic from the client. The one proposed by the question author him/herself is basically a hack that requires keeping the API key on the client which is very insecure.
The main reason why it is not allowed is that it would let adversary to tamper with the client and send spam messages to other users.

NSMutableURLRequest returning JSON with empty sub-arrays

I have created a method that uses NSMutableURLRequest to request and receive JSON from a RESTful API running on a remote machine. The request successfully returns some JSON, but the returned sub-arrays in the JSON (see tasks: []) are empty.
The JSON returned from the API is:
{
"error":false,
"tasks":[
{
"id":1,
"task":"Get Milk",
"status":0,
"createdAt":"2014-08-09 12:29:15"
},
{
"id":2,
"task":"Call Mom",
"status":0,
"createdAt":"2014-08-09 12:46:52"
},
{
"id":3,
"task":"Call Dad",
"status":0,
"createdAt":"2014-08-09 12:47:04"
},
{
"id":4,
"task":"Study",
"status":0,
"createdAt":"2014-08-09 12:47:08"
}
]
}
The method that utilizies NSMutableURLRequest (proper parameters being passed is assumed) is:
-(NSDictionary *) apiRequestWithEndpoint:(NSString *) endpoint
withParams:(NSDictionary *) params
withHTTPHeaders:(NSDictionary *) headers
withHTTPMethod:(NSString *) method
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:endpoint]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:method];
//set headers
for (id key in headers) {
[request setValue:[headers valueForKey:key] forHTTPHeaderField:key];
}
//set paramaters in request body
NSMutableString *requestBody = [[NSMutableString alloc] init];
int keyIndex = 0;
for (id key in params) {
if (keyIndex == 0) {
[requestBody appendFormat:#"%#=%#", key, [params valueForKey:key]];
} else {
[requestBody appendFormat:#"&%#=%#", key, [params valueForKey:key]];
}
keyIndex++;
}
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *NSURLError = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLError];
if (NSURLError) {
NSLog(#"Error: %# Cancelling operation.", NSURLError);
return nil;
}
NSError *NSJSONSerializationError = nil;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&NSJSONSerializationError];
if (NSJSONSerializationError) {
NSLog(#"Error: %# Cancelling operation.", NSJSONSerializationError);
return nil;
}
NSLog(#"Data: %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return responseJSON;
}
Notice the 4th last line that logs the returned NSData from the NSMutableURLRequest, the output is:
Data: {"error":false "tasks":[]}
The code that calls the above method:
NSString *getAllTasksEndpoint = #"http://developmentVPS.com/TaskList-API/v1/tasks";
NSString *apiKey = #"A Valid API Key";
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:apiKey, #"Authorization", nil];
NSDictionary *responseJSON = [self apiRequestWithEndpoint:getAllTasksEndpoint
withParams:nil
withHTTPHeaders:headers
withHTTPMethod:#"GET"];
It is my understanding that the entire data returned from the request should be logged in that NSLog call, but "tasks" is empty. I am new to iOS development, so I may be missing something simple. Does anybody see anything I am missing here?

NSURLConnection wrong order

I have a NSURLConnection (two of them), and they're running in the wrong order.
Here's my method:
- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password {
NSURL *url = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
//Create and send request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"Pin=%#&Password=%#",
[self percentEscapeString:pin],
[self percentEscapeString:password]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// do whatever with the data...and errors
if ([data length] > 0 && error == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from login), it was = %#", loggedInPage);
}
}
else {
NSLog(#"error: %#", error);
}
}];
//Now redirect to assignments page
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError)
{
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from home), it was = %#", homePage);
}
}
else {
NSLog(#"error: %#", homeError);
}
}];
}
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
So, it's two NSURLConnection's that are added to the [NSOperationQueue mainQueue]. What my output is showing me is that the second NSURLConnection is running before the first one. So it tries to go to the page where I download data before I'm logged in, so it (obviously) returns a "You're not logged in" error.
How do I schedule them one after another?
The issue, as I suspect you have realized, is that you're doing asynchronous network requests (which is good; you don't want to block the main queue), so there's no assurance of the order they'll finish.
The quickest and easiest answer is to simply put the call to the second request inside the completion block of the first one, not after it. You don't want to be making that second one unless the first one succeeded anyway.
To keep your code from getting unwieldy, separate the login from the request for main page. And you can use the completion block pattern which is common with asynchronous methods. You add a parameter to loginToMistarWithPin that specifies what it should do when the request finishes. You might have one completion block handler for success, and one for failure:
- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password success:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
NSURL *url = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
//Create and send request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"Pin=%#&Password=%#",
[self percentEscapeString:pin],
[self percentEscapeString:password]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// do whatever with the data...and errors
if ([data length] > 0 && error == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
// assuming you validated that everything was successful, call the success block
if (successHandler)
successHandler();
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from login), it was = %#", loggedInPage);
if (failureHandler)
failureHandler();
}
}
else {
NSLog(#"error: %#", error);
if (failureHandler)
failureHandler();
}
}];
}
- (void)requestMainPage {
//Now redirect to assignments page
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:#"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError)
{
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from home), it was = %#", homePage);
}
}
else {
NSLog(#"error: %#", homeError);
}
}];
}
Then, when you want to login, you can do something like:
[self loginToMistarWithPin:#"1234" password:#"pass" success:^{
[self requestMainPage];
} failure:^{
NSLog(#"login failed");
}];
Now, change those successHandler and failureHandler block parameters to include whatever data you need to pass back, but hopefully it illustrates the idea. Keep your methods short and tight, and use completion block parameters to specify what an asynchronous method should do when it's done.
Can you check the below link. It is about forcing one operation to wait for another.
NSOperation - Forcing an operation to wait others dynamically
Hope this helps.

Convert JSON feed to NSDictionary

Where JSON_CATEGORY_DATA_URL_STRING is my feed URL, which returns fine as:
[
{
"group":"For Sale",
"code":"SSSS"
},
{
"group":"For Sale",
"category":"Wanted",
"code":"SWNT"
}
]
I cannot seem to get a nice NSDictionary (or NSArray) out of the following code:
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_string;
}
I've read many posts on this, but am not getting it.
With IOS5 you can use NSJSONSerialization for serializing the JSON.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.
I made a class that makes this task easier. It uses iOS 5's NSJSONSerialization. Clone it from github here.
You need to use JSON parser. here is the edited code
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
this should be the code to get the NSDictionary. but you json string is an array so instead use .
+ (NSArray *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
Edit:
you need to use JSON.framework to call JSONValue method.
also you need to return json_dict instead of json_string as json_string is of NSString type and not NSDictionary or NSArray.
and dont autorelease it, as it is your class variable
create method to fetchjson data.Pass your url in urlwithstring.
-(void)fetchjsondata
{
NSString *login= [[NSString stringWithFormat:#"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"----%#", login);
NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#", dic_property);
NSLog(#"counts=%d",[[dic_property objectForKey:#"Data"]count]);
}
else {
NSLog(#"network error, %#", [error localizedFailureReason]);
}
});
}];
}
call fetchjsonmethod in anywhere.
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];

Resources