Objective - C Connection Test Warnings - iphone

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];
}
}

Related

I get 'deprecated' warnings in Xcode 4.5.2

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.)

Want to get my captured video back

I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}

How to pase a JSON array in iphone sdk?

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/

iphone app exit with "No SIM card installed"

I use the MFMessageComposeViewController for sending in App sms. in iPhone 4.0, if there is no SIM card, the app exits. it just gives a pop up message "no sim card installed".
The delegate callback MessageComposeResultSent. But application exits. Is there any way to prevent it from exiting? or how to check if there is any SIM card in the phone?
Code snippets below:
/* Open the system sms service, copying the sms text in system clipboard. */
- (void) sendSMSAsURLRequest {
NSString *phoneNumber = friend.phoneMobile;
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
NSString *textUTIType = (NSString *)kUTTypeUTF8PlainText; // add MobileCoreServices.framework for this type.
[pasteBoard setValue:[self buildSMSText] forPasteboardType:textUTIType];
NSString *urlString = [NSString stringWithFormat:#"sms:%#", phoneNumber];
NSURL *url = [[NSURL alloc] initWithString: urlString];
[[UIApplication sharedApplication] openURL: url];
[url release];
}
-(void) sendInAppSMS {
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
controller.delegate = self;
if([MFMessageComposeViewController canSendText])
{
NSString *smsText = [self buildSMSText];
controller.body = smsText;
controller.recipients = [NSArray arrayWithObjects:friend.phoneMobile, nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result) {
case MessageComposeResultCancelled:
NSLog(#"Cancelled");
break;
case MessageComposeResultFailed:{
NSString *alertString = NSLocalizedString(#"Unknown Error. Failed to send message", #"");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
break;
}
case MessageComposeResultSent:
NSLog(#"SMS sent");
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
To Detect Sim Card is installed or not use following Code :
#import CoreTelephony;
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No SIM Card Installed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else{
//Paste Your code here
}
The work around I am using now is, a flag in the app delegate,
- (void)applicationWillResignActive:(UIApplication *)aNotification {
if (shouldExitApp) {
exit(0);
}
}
In the SMS sending view controller,
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = NO;
And set the flag again, when in the SMS sending view controller,
- (void) viewDidAppear:(BOOL)animated {
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = YES;
[super viewDidAppear:animated];
}

Resolving the wait situation for a detached thread in IPhone?

I am using a private MBProgressHUD
Now I am using the indicator view on my add button in which I am calling my addrecord service .
UIWindow *window = [UIApplication sharedApplication].keyWindow;
HUD = [[MBProgressHUD alloc] initWithWindow:window];
// Add HUD to screen
[window addSubview:HUD];
// Regisete for HUD callbacks so we can remove it from the window at the right time
HUD.delegate = self;
// Show the HUD while the provided method executes in a new thread
[HUD showWhileExecuting:#selector(addingToFavorites) onTarget:self withObject:nil animated:YES];
the adding to favorites method :
NSURL *url = [NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
//[request setTimeoutInterval:10];
//NSURLResponse *response = nil;
// NSError *error = nil;
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSData *data1= [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
if(data1 == nil)
{
doneFlag = NO;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert"
message:#"The network is not available.\n Please check the Internet connection."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
doneFlag = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Confirmation"
message:#"Added To favorites"
delegate:nil
cancelButtonTitle:#"OKAY"
otherButtonTitles:nil];
[alert show];
alert = nil;
[alert release];
}
[request release];
This is all running fine except the instruments gives leak of the uialertview may be it is conflicting with the mbprogreshud.
So I thought to remove the alert from the calling method and put it in the caller the method like this:
the caller method now :
UIWindow *window = [UIApplication sharedApplication].keyWindow;
HUD = [[MBProgressHUD alloc] initWithWindow:window];
// Add HUD to screen
[window addSubview:HUD];
// Regisete for HUD callbacks so we can remove it from the window at the right time
HUD.delegate = self;
// Show the HUD while the provided method executes in a new thread
[HUD showWhileExecuting:#selector(addingToFavorites) onTarget:self withObject:nil animated:YES];
//it should wait for the above line to be executing ******* then to exexute the be //below condition but how ?
if (doneFlag == NO) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert"
message:#"The network is not available.\n Please check the Internet connection."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
} else {
[favoritesButton setTitle:#"Remove" forState:UIControlStateNormal];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Confirmation"
message:#"Added To favorites"
delegate:nil
cancelButtonTitle:#"OKAY"
otherButtonTitles:nil];
[alert show];
alert = nil;
[alert release];
}
the adding to favorites method :
NSURL *url = [NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
//[request setTimeoutInterval:10];
//NSURLResponse *response = nil;
// NSError *error = nil;
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSData *data1= [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
if(data1 == nil)
{
doneFlag = NO;
}
else
{
doneFlag = YES;
}
[request release];
In the launching of the progresshud thread is detaching something like this :
[NSThread detachNewThreadSelector:#selector(launchExecution) toTarget:self withObject:nil]
Now My question is that If I follow the first scenario . How can I assure the the alertview leak will not come
Or If I am following the second scenario How can I assure the if condition will be executed after completing this line executed :
[HUD showWhileExecuting:#selector(addingToFavorites) onTarget:self withObject:nil animated:YES];
Regarding the first scenario, it is in general a bad idea to do UI updates from threads other than the applications main thread. UIKit is NOT thread safe and doing threaded UI updates can cause all sorts of strange things to happen. Now, I'm not sure if this is the cause for the leak but I would avoid showing an UIAlertView in addingToFavorites. Use performSelectorOnMainThread or the second scenario described below.
Regarding the second scenario, move everything below the showWhileExecuting call to the hudWasHidden delegate method. At this point you can be sure that your code was fully executed and the doneFlag was set.
To use performSelectorOnMainThread, define a new method, put your code in it and than call performSelectorOnMainThread.
I.e.,
- (void)showAlert {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"The network is not available.\n Please check the Internet connection." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
Call with,
[self performSelectorOnMainThread:#selector(showAlert) withObject:nil waitUntilDone:NO];
I would go with the second scenario though.
Other answers notwithstanding, you were creating the UIAlertView leak with this sequence:
[alert show];
alert = nil;
[alert release];
The last two lines should be swapped:
[alert show];
[alert release];
alert = nil;