NSURL *jsonURL = [NSURL URLWithString:#"http://ambiguous.dubbelzinnig.com/index.php? get_cat=1"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
if (jsonData == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Webservice Down" message:#"The webservice you are accessing is down. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else {...
It appears that initWithContentsOfURL needs to be changed, but I have tried what it said in the developer's guide, but I cannot get it to work...can somebody fix this code please?
Thanks so much!
Use initWithContentsOfURL:encoding:error: or initWithContentsOfURL:usedEncoding:error: instead.
For example:
NSURL *jsonURL = [NSURL URLWithString:#"http://ambiguous.dubbelzinnig.com/index.php?get_cat=1"];
NSError *error = nil;
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:&error];
if( error == nil ) {
// Parse jsonData
} else {
// There was a problem
}
You'll want to replace the encoding value with an enum for the actual encoding type. There are many enums for this purpose available in the NSString class... see the "String Encodings" section in: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Why don't you take a look in the documentation?
initWithContentsOfURL:
Initializes the receiver, a newly allocated NSString object, by reading data
from the location named by a given URL. (Deprecated in OS X v10.4. Use
initWithContentsOfURL:encoding:error: or
initWithContentsOfURL:usedEncoding:error: instead.)
Related
I have a static file path to a download folder, files download fine but when I download a new one the old one gets replaced by new. I suppose because of static pathing. How do I add a timestamp to my code so whenever a new download is made the old one wouldn't get replaced?Or maybe even give download file the "original" filename from the actual array?
here is my download code:
-(void) Savefile {
[self.downloadfile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wooopss!" message:#"Download failed. Try Again..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else if (data) {
[data writeToFile:#"/Users/Danny/Desktop/PDFFile/hello.pdf" atomically:NO ];
NSLog(#"Downloading file...");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Downloading" message:#"File is being downloaded..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"MMddYYYYmmss"];
NSString *filePath = [NSString stringWithFormat:#"/Users/Danny/Desktop/PDFFile/hello_%#.pdf", [dateFormatter stringFromDate:[NSDate date]]];
Which will give you this:
/Users/Danny/Desktop/PDFFile/hello_032620144401.pdf
Not entirely sure what you mean by:
Or maybe even give download file the "original" filename from the
actual array
i have write a NSDictionary Category. The Category has a method calls "initWithJSONURL".
Here the code:
- (id)initWithJSONURL:(NSURL *)url
{
self = [super init];
if (self) {
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:url
options:NSUTF8StringEncoding
error:&error];
if (!data) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"connection failed"
message:[error localizedDescription]
delegate:self
cancelButtonTitle:#"cancel"
otherButtonTitles:nil];
[alert show];
} else {
self = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"invalid data"
message:[error localizedDescription]
delegate:self
cancelButtonTitle:#"cancel"
otherButtonTitles:nil];
[alert show];
}
}
}
return self;
}
And here the code from my ViewController viewDidLoad
NSURL *url = [NSURL URLWithString:#"http://localhost:8888/json.php"];
NSDictionary *dict = [[NSDictionary alloc] initWithJSONURL:url];
NSLog(#"%#", dict);
If I use an correct URL everything works perfect.
But if the URL not correct, the App crash.
I don't know why, it should not crash, it should show the alert View.
The consoles show:
erminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSDictionary count]: method sent to an uninitialized immutable dictionary object'
I hope anybody can help me and sorry for my bad english.
You want to call [self init] instead of [super init]. A category is not a subclass, so [super init] means [NSObject init]. The designated initializer of NSDictionary is never called and the internal dictionary structures are staying unitiliazed.
I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/
I want to check the app version from apple so I send request like below
- (void)connectToCheckVersion{
NSString *url = #"http://itunes.apple.com/lookup?id=466424846";
TTURLRequest *_request = [TTURLRequest requestWithURL:url delegate:self];
_request.httpMethod = #"GET";
_request.cachePolicy = TTURLRequestCachePolicyNone;
_request.shouldHandleCookies = NO;
TTURLJSONResponse* response = [[TTURLJSONResponse alloc] init];
_request.response = response;
TT_RELEASE_SAFELY(response);
[_request send];
}
- (void)requestDidFinishLoad:(TTURLRequest*)request {
TTURLJSONResponse* response = request.response;
NSDictionary* json = response.rootObject;
NSArray *results = [json objectForKey:#"results"];
NSString *version;
for (NSDictionary *rawResult in results) {
version = [rawResult objectForKey:#"version"];
}
NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"];
if (version != nil && currentVersion != nil && ![version isEqualToString:currentVersion]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"info"
message:#"newer version"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
and after [_request send]; will get [CFString release]: message sent to deallocated instance 0x6a83e00. I checked all Strings in this method seems they are ok, and I can still get correct response from remote.
If I comment out this connectToCheckVersion method then no any problem.
Any diea?
I think that you should retain the _request variable and save it as a member.
Because it will autorelease after the function is returned.
You have to release it after the request is successed or failed.
Thank you.
I have the following code:
//View guest list
-(IBAction) guestList:(id) sender{
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"myURL"]];
//Waits a set peroid of time
wait(20000);
//Guest list is availible
if (connected != NULL){
CHARLIEAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate displayView:6];
}
//No network connection availible
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Network Connection!" message:#"Cannot establish internet connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
And I get the following warnings:
//Waits a set peroid of time
wait(20000);
Gives me -
warning: passing argument 1 of 'wait' makes pointer from integer without a cast
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://photostiubhart.comoj.com/testconnection.php"]];
Gives me -
warning: 'stringWithContentsOfURL:' is deprecated (declared at /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSString.h:384)
I've done my testing and the code SEEMS to work fine, even though there are these warnings. Is there a way to remove these warnings at all? Or do they not matter?
I'm using xCode version 3.2.6
Thanks,
Jack
use
NSError* error;
NSString* connected = [NSString stringWithContentsOfURL:TheUrl encoding:NSASCIIStringEncoding error:&error];
You should use the method -
+(id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
for example -
NSString* text = [NSString stringWithContentsOfURL:TheUrl encoding:NSASCIIStringEncoding error:&error];
Hope it will help you.
Try doing it this way:
-(IBAction)guestList:(id) sender{
NSURL *requestUrl = [NSURL URLWithString:#"http://photostiubhart.comoj.com/testconnection.php"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:requestUrl];
NSData *loadTest = [NSData dataWithContentsOfURL:requestUrl];
if (loadTest == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Network Connection!" message:#"Cannot establish internet connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
} else {
CHARLIEAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate displayView:6];
}
}