Whats wrong with simple html NSString? - html

Hey guys I have a simple html NSString, it works fine on the browser but does not load on the iPhone. I am using a simple: [self.w loadHTMLString:errorString baseURL:nil]. What am I missing?
NSString* errorString = [NSString stringWithFormat:
#"<html><body> <iframe src=\"http://64.183.101.142:81/pda.htm\"width=\"500\" height=\"500\"></iframe></body></html>"];

Yo need to first load your request or HTML on webview and Capture this request using a UIWebViewDelegate method with following protocol
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//capture request => request
//From here you have the NSURLRequest object
//You can extract the headers of the request to NSDictionary which will contain //the
//authentication cookie details, token, etc. using the following method of NSURLRequest
//- (NSDictionary *)allHTTPHeaderFields
}
Source Source link

If it requires authentication you will need to modify your string depending on the type of request.
if it's a get it will have a "?" at the and the parameters something like this:
http://xx.xx.xx.xx:81/pda.htm?user="userX"&passwd="something" if it's a post method you will pass your data within the body of your request. [NSURLRequest setHTTPBody:];
I hope this helps.

Related

parsing json from url to swift 2.0

I've been trying to retreive my json data for my iOS App. I tried many different sollutions but none of these worked properly for me. So this was the code I was using to read the json from the url and convert it.
let url = NSURL(string: "http://www.blind3d.byethost7.com/service.php")!
func load() {
do {
let request = NSURLRequest(URL: url)
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
self.handleData(data)
}
catch let error as NSError {
print("wieso dont you do siss : \(NSURLRequest(URL: url))")
self.handleError(error)
}
}
func handleError(error : NSError?) {
print("wieso dont you do siss : \(NSURLRequest(URL: url))")
NSLog("%#", "Error with loading from \(url): \(error)")
}
func handleData(data : NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
handleJSON(json)
}
catch let error as NSError {
handleError(error)
}
}
but somehow this isn't running properly. I am always getting this error when I am executing this method: NSJSONSerialization
Error with loading from http://www.blind3d.byethost7.com/service.php: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})
The json data I wanted to use for my app is here
Thank you for your help guys
The problem occurs because there it no actual JSON in the data variable. I tried your web service, and this is what you get returned in the data, along with all the other error html tags:
"This site requires Javascript to work, please enable Javascript in your
browser or use a browser with Javascript support"
The full response:
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("26049265c821fd7227c09955cbb61ebc");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://www.blind3d.byethost7.com/service.php?ckattempt=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
This seems to happen, because there is some Javascript injected in the webpage you are trying to parse from, probably for statistics, or some other unknown reasons.
For checking by yourself, print your data - print(data), before calling self.handleData(data)
Try removing \r\n or escape them with '\' like
\\r\\n
and you are good to go. BTW, using json is painful in swift like this, SwiftyJSON is a necessary library if you deal with json frequently.
This is the result of installed "testCookie-nginx-module"
It's supposed to prevent DDOS attacks on your hosting
When you visit your site for the first time, it sends you this JS code, which your browser is supposed to process and set a special cookie (its name it _test)
Only with this cookie attached to your IP your browser can see the original content (your content: html php json etc.)
Seems the only way for you - is to process this JS (with AES, HEX and other JS functions, get the right _test cookie and send another request with this cookie)

iOS NSURLSession Get Request JSON always showing outdated data

I have the following doubts about the JSON data returned from using both "GET" versus "POST" request. In the following URL JSON DATA, the data is not always updated based on the server changes (eg: database). For example, if I delete all the suggestion records from the database when I had 3 previously, it still returns 3 suggestion records in my JSON response body when I call dataTaskWithRequest.
However, if I change to POST, then the JSON response body will always be updated with the actual records from the server. In my server code (Using CakePHP), I did not check for post or get data. Actually, it was intended to be a GET method, but for some reason, only POST method seems to always fetch the most up to date data from JSON as opposed to GET.
Below is my code from my iOS client, but I'm not too sure if its very useful. I was wondering if there is a cache issue for GET request as opposed to POST request? However, I tried disabling cache for NSURLSessionConfig but it had no impact.
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
The code base is below:
NSString *requestString = [NSString stringWithFormat:#"%#/v/%#.json", hostName, apptIDHash];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (httpResp.statusCode == 200) {
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
[self printJSONOutputFromDictionary:jsonObject];
if (!jsonError) {
block(jsonObject, nil);
}
else{
block(nil, jsonError);
}
}
else{
NSError *statusError = [self createServerUnavailableNSError:httpResp];
block(nil, statusError);
}
}
else{
block(nil, error);
}
}];
[dataTask resume];
In the above code fragment, the JSON body is always showing outdated data.
I really want to understand the issue, and would really appreciate if anyone could explain this issue for me.
Try adding the following request header:
[req addRequestHeader:#"Cache-Control" value:#"no-cache"];
I encountered the same problem as you and adding the above code solved the problem for me.
Taken from ASIHTTPRequest seems to cache JSON data always

Restkit 0.22.0 how to map a simple JSON response with no keyPath to post

For simplicity the Rest API, sends this JSON response-body= { "status" : "ok"}.
I set-up my Restkit mappings like... created a Class called StatusResponse which has one #property (nonatomic, assign) NSString *status;
RKObjectMapping *statusResponseMapping = [RKObjectMapping mappingForClass:[StatusResponse class]];
[statusResponseMapping addAttributeMappingsFromDictionary:#{#"status":#"status"}];
// also tried : [statusResponseMapping addAttributeMappingsFromDictionary:#[#"status"]]; which resulted in same error
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *statusResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:statusResponseMapping method:RKRequestMethodPOST pathPattern:#"status" keyPath:nil statusCodes:statusCodes];
[[RKObjectManager sharedManager] addResponseDescriptor:statusResponseDescriptor];
I'm running a post which is successful, but I get this error back:
NSUnderlyingError=0x17024d440 "No mappable object representations were found at the key paths searched.", keyPath=null, NSLocalizedDescription=No response descriptors match the response loaded.}
response.body={
"status": "ok"
}
Any help with this would be appreciated.
You should try keyPath to #"" and pathPattern as nil, here is piece of Code I am using which is perfectly working fine for me. I am doing exactly same you are trying to do.
RKResponseDescriptor *statusResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[ResponseStatus rkObjectMappingForResponse:YES] method:RKRequestMethodAny pathPattern:nil keyPath:#"" statusCodes:statusCodes];
Because your response descriptor has pathPattern:#"status", the mapping will only be used when you make a request to the status path on your server. That probably isn't what you want.
You should probably use pathPattern:nil.

I'm making an IOS application, how do I make the application send me the UDID of the device its on?

Im currently developing and IOS application, For security purposes I would like to know how I can make the app send the device "UDID" to a server.
So basically I need to know how to make the device "fetch" the udid and then take the udid and send it to a server as a "request".
If the UDID is "registered" in the MYSQL database, then the server will send back a confirmation.
Besides finding out how to get the udid, I may need additional help setting up the mysql database :$
Thanks!
You can get the UUID of an iOS device using: CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);
(Apple dont like you to use the UDID).
As far as posting it to a server, I suggest using a JSON post method, and recording the success. A good JSON library is SBJson which can be found here. Youll need to create a HTTP post, get the response data, and use SBJson library to parse the response.
EDIT: OR instead of SBJson, as Carbonic acid kindly pointed out, you can use NSJSONSerialization. Also, as pointed out by Naz Mir, new UUID method used.
Edit:
[[[UIDevice currentDevice] identifierForVendor] UUIDString] is not deprecated as I stated. Please go through the links below for information.
Getting UDID as stated above NSString *uuididentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; is deprecated and Apple no longer allows it. If your aim is to uniquely identify a device you can use SecureUDID or OpenUDID
I have used OpenUDID sometime back in one of our apps and using it is as simple as -
#import "OpenUDID.h"
[OpenUDID setOptOut:NO];
self.openUDID = [OpenUDID value];
Once you have the required value sending it to the server is trivial. You can use iOS networking library like AFNetworking to send and receive data. For example,
#import "AFHTTPRequestOperation.h"
NSURL *url = [NSURL URLWithString:#"Your sever URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *postString = [NSString stringWithFormat:#"&UDID=%#", self.
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *httpOperation, id responseObject) {
//handle server response here
NSLog(#"%#", [httpOperation responseString]); //this contains the servers response
}failure:^(AFHTTPRequestOperation *httpOperation, NSError *error) {
//handle server errors here
NSLog(#"error: %#", [httpOperation error]);
}];

Modify a repo to get JSON asynchronously

I'm working on an iPhone app that needs to load data from my server in JSON or XML format. Since the app is free, I get huge amount of data and I get crash when launching app due to the long time when loading the data. So I understand that I should not get "all" the JSON at once but I have to load the data "pagened" [ little by little ] ..
I found this project that suits well my needs but can't get succes to modify it to my need :
https://github.com/nmondollot/NMPaginator
The project tooks Twitter api as a data source, what if I need to deal with a simple php file that returns JSON formatted data?
nb: I tried to contact the project developer after I tried to modify, but didn't get answer until now.
Thanks.
The easiest solution could be to just download the data in another thread. This can be done in many ways but one way to do it is by using grand central dispatch (GCD).
Something like this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSURL *url = [NSURL URLWithString:#"Your_URL"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue currentQueue]
completionHandler:
^(NSURLResponse *res, NSData *data, NSError *err) {
// Convert the data to appropriate object
NSString* myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//You would probably deserialize the json here
//self.tableViewArray = serialiedObjects;
 
dispatch_async(dispatch_get_main_queue(), ^{
//Reload table view
[self.tableView reloadData];
});
}];
});