xcode textfield to NSURL path - xcode

I am trying to get a URL from my user in a TextField and then process the result. Presently an exception is being thrown with the following -[UITextField length]: unrecognized selector sent to instance in the NSURLRequest below when I supply URLWithString: (NSString *)self.urlNameInput].
myViewController.h
#class myViewController;
#interface myViewController : UIViewController <UITextFieldDelegate, NSURLConnectionDataDelegate, NSURLConnectionDelegate>
{
NSMutableData *receivedData;
}
#property (weak, nonatomic) IBOutlet UITextField *urlNameInput;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#end
myViewController.m
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == self.urlNameInput) {
[textField resignFirstResponder];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString: (NSString *)self.urlNameInput] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [NSMutableData data] ;
} else {
// Inform the user that the connection failed.
NSLog(#"Their is an error with that URL.");
}
}
return YES;
}

I think your mistake is, that you pass an UITextField to a method expecting a NSString.
Change
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString: (NSString *)self.urlNameInput] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
to
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

Related

Cocoa POST issue

I´m newbie with Cocoa. I have one issue when I want to send data to my WS via POST
I have RequestPost program to inherit on all my projects
//
// RequestPost.h
//
// Created by Roberto on 10/01/13.
// Copyright (c) 2013 CEM. All rights reserved.
//
#import <Foundation/Foundation.h>
#protocol DelegadoRedPost <NSObject>
-(void) terminaDescarga:(NSData*)datos conID:(NSInteger) id;
-(void) errorDescarga:(NSInteger)codigo conID:(NSInteger) id;
#end
#interface RequestPost : NSObject <NSURLConnectionDelegate>
#property (strong, nonatomic) NSObject <DelegadoRedPost> *delegado;
#property (nonatomic) NSInteger id;
#property (nonatomic, strong) NSMutableData *buffer;
#property (nonatomic, strong) NSURLConnection *conexion;
-(void)descargar:(NSString*)direccion datosPost:(NSString*)datos conId:(NSInteger)id;
#end
//
// RequestPost.m
//
// Created by Roberto on 10/01/13.
// Copyright (c) 2013 CEM. All rights reserved.
//
#import "RequestPost.h"
#implementation RequestPost
-(void)descargar:(NSString*)direccion datosPost:(NSString*)datos conId:(NSInteger)id
{
self.id = id;
NSURL *url = [NSURL URLWithString:direccion];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//NSString *strLength = [NSString stringWithFormat:#"%d", datos.length]; aqui comento 18 abr 2016
NSString *strLength = [NSString stringWithFormat:#"%lu", (unsigned long)datos.length];
[req addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req addValue:strLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[datos dataUsingEncoding:NSUTF8StringEncoding]];
self.conexion = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if(self.conexion){
self.buffer = [NSMutableData data];
}
}
#pragma mark - Métodos del Delegado de NSURLConnection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.buffer.length = 0;
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.buffer appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.delegado terminaDescarga:self.buffer conID:self.id];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.delegado errorDescarga:error.code conID:self.id];
}
#end
Now, when I want to inherit last files I have gotten an error .... Incompatible pointer types assigning to NSObject ... In the line request.delegado = self;
This is the code when inherit
-(void) request
{
RequestPost *request = [[RequestPost alloc] init];
request.delegado = self;
NSString *postStr = [NSString stringWithFormat:#"datos=%#",self.json];
NSString *strUrl = #"http://www.futho7.com/WebService/subir_datos.php";
[request descargar:strUrl datosPost:postStr conId:100];
}
How can I fix it?
Thanks & Regards
In the .m file that contains the request method, you need to indicate that the class conforms to the DelegadoRedPost protocol and implement the required protocol methods.
Add this just before the #implementation line:
#interface WhateverClassNameThisIs () <DelegadoRedPost>
#end
Obviously replace WhateverClassNameThisIs with the actual name of this class.
As a side note, you should change the declaration of the delegado property from:
#property (strong, nonatomic) NSObject <DelegadoRedPost> *delegado;
to:
#property (weak, nonatomic) id<DelegadoRedPost> *delegado;
Note the two changes - delegates should normally be weak, not strong. This avoids reference cycles. And the type should be with id, not NSObject. The protocol itself extends the NSObject protocol.

Core Loation not outputing current location

I've been working on a app that displays the current location of the user in a UILabel using the core location framework in Xcode When a button is clicked the app calls the CLLocationManager that gets the users latitude and longitude. I also included reverse geocoding to present the coordinates in a human readable form. I have this code here.
Header file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (strong, nonatomic) IBOutlet UILabel *latitudeLabel;
#property (strong, nonatomic) IBOutlet UILabel *longitudeLabel;
#property (strong, nonatomic) IBOutlet UILabel *addressLabel;
- (IBAction)getCurrentLocation:(id)sender;
#end
Implementation file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController {
CLLocationManager *locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
_longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end
I got this output
Message from debugger: Terminated due to signal 15

Unable to use AVAudioRecorder, bad access on com.apple.audio.IOThread.client

I'm working on a simple Cocoa application that retrieve the meters from an AVAudioRecorder.
Here is my code:
#interface AppDelegate () <AVAudioRecorderDelegate>
#property (weak) IBOutlet NSWindow *window;
#property (strong) AVAudioRecorder *recorder;
#property (strong) NSURL *dump;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSDictionary *settings = #{AVSampleRateKey: #(44100.0),
AVNumberOfChannelsKey: #2,
AVFormatIDKey: #(kAudioFormatAppleLossless),
AVEncoderAudioQualityKey: #(AVAudioQualityHigh)
};
NSError *error = nil;
self.dump = [[NSURL alloc] initFileURLWithPath: [NSTemporaryDirectory() stringByAppendingString: #"dump"]];
self.recorder = [[AVAudioRecorder alloc] initWithURL: self.dump
settings: settings
error: &error];
NSLog(#"Recorder, got error? %#", error);
self.recorder.delegate = self;
[self.recorder prepareToRecord];
self.recorder.meteringEnabled = YES;
[self.recorder record];
}
#end
I also have a timer that retrieves the meters every second. It works on my laptop but on my iMac, for some reason I have a BAD_ACCESS on "com.apple.audio.IOThread.client (8)" when I call record.
Any idea ?
Thanks!

How do I make GCDAsyncSocket that is declared in AppDelegate available to view controllers

Following a post of similar question (which doesn't work), I declared a instance of GCDAsyncSocket on AppDelegate.h
#import <UIKit/UIKit.h>
#class ViewController;
#class GCDAsyncSocket;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
GCDAsyncSocket *asyncSocket;
}
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, retain) GCDAsyncSocket *asyncSocket;
#property (strong, nonatomic) ViewController *viewController;
#end
and do the socket initialization in AppDelegate.m
#import "AppDelegate.h"
#import "GCDAsyncSocket.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize asyncSocket;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
dispatch_queue_t mainQueue = dispatch_get_main_queue();
self.asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
NSString *host = #"10.1.100.50";
uint16_t port = 3040;
NSError *error = nil;
if (![self.asyncSocket connectToHost:host onPort:port error:&error])
{
NSLog(#"Error connecting: %#", error);
}
char bytes[] = "run";
NSData* requestData = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];
[self.asyncSocket writeData:requestData withTimeout:-1 tag:0];
return YES;
}
The I tried to access the socket from multiple view controllers by invoking:
GCDAsyncSocket *asyncSocket = [[[UIApplication sharedApplication] delegate] asyncSocket];
the code completion stops at [[UIApplication sharedApplication] delegate] without being able to suggest asyncSocket.
What should I do to make asyncSocket accessible in multiple view controllers when the instance of asyncSocket is being declared in AppDelegate? Thanks!
Here's my Xcode project file : http://bit.ly/PLe1Le
You are on the right track. And the application delegate is a great place for a socket connection. I think you're being tripped up by something relatively simple.
[[UIApplication sharedApplication] delegate] returns an id or generic object pointer to an object that conforms to the <UIApplicationDelegate> protocol. So code completion has no way of knowing that your application's delegate is an instance of your AppDelegate class.
Remember if you are in fact using an instance of AppDelegate to be your application's delegate then [[UIApplication sharedApplication] delegate] will return a pointer to your delegate, but it will be the generic pointer discussed above.
The simplest solution is to cast the pointer you receive back from [[UIApplication sharedApplication] delegate] to be a pointer of AppDelegate type.
For example:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// We now have a pointer to your app delegate that the compiler knows is an AppDelegate.
// So code completion will work and it will compile.
GCDAsyncSocket *socket = [myAppDelegate asyncSocket];
Or you can stack the calls to one statement. The syntax looks a little funky, but this is how it's done.
GCDAsyncSocket *socket = [(AppDelegate *)[[UIApplication sharedApplication] delegate] asyncSocket];

xCode Console Errors when recording Audio

I get the following console errors when recording a sound.. Any ideas what I'm doing wrong? The recordings work, except that the outputs are REALLY soft.
TIA
2011-04-17 12:51:25.707 FlashCards[18561:1210f] Cannot find executable for CFBundle/CFPlugIn 0x5a64780 </Library/Audio/Plug-Ins/HAL/DVCPROHDAudio.plugin> (not loaded)
2011-04-17 12:51:25.708 FlashCards[18561:1210f] Cannot find function pointer NewPlugIn for factory C5A4CE5B-0BB8-11D8-9D75-0003939615B6 in CFBundle/CFPlugIn 0x5a64780 </Library/Audio/Plug-Ins/HAL/DVCPROHDAudio.plugin> (not loaded)
2011-04-17 12:51:25.712 FlashCards[18561:1210f] Cannot find executable for CFBundle/CFPlugIn 0x5c69e90 </Library/Audio/Plug-Ins/HAL/iSightAudio.plugin> (not loaded)
2011-04-17 12:51:25.713 FlashCards[18561:1210f] Cannot find function pointer iSightAudioNewPlugIn for factory 9BE7661E-8AEF-11D7-8692-000A959F49B0 in CFBundle/CFPlugIn 0x5c69e90 </Library/Audio/Plug-Ins/HAL/iSightAudio.plugin> (not loaded)
2011-04-17 12:51:25.729 FlashCards[18561:c503] start recording
As requested, I am adding code:
.h file snippet:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AudioToolbox/AudioToolbox.h>
#protocol BackViewControllerDelegate;
#interface BackViewController : UIViewController <UITextViewDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate, UIAlertViewDelegate>
{
AVAudioRecorder *audioRecorder;
AVAudioPlayer *audioPlayer;
IBOutlet UIButton *playButton;
IBOutlet UIButton *recordButton;
IBOutlet UIActivityIndicatorView *autoCog;
BOOL toggle;
}
#property (nonatomic, retain) IBOutlet UIButton *playButton;
#property (nonatomic, retain) IBOutlet UIButton *recordButton;
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *autoCog;
-(IBAction) recordAudio;
-(IBAction) playAudio;
.m snippet
#synthesize playButton;
#synthesize recordButton;
#synthesize autoCog;
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"%s", __FUNCTION__);
[super viewWillAppear:animated];
//Start the toggle in false mode. PREMISE: WHEN WE GET HERE FIRST, WE ARE NOT RECORDING
toggle = NO;
NSError *error = nil;
//Instantiate an instance of the AVAudioSession object.
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
//Activate the session
[audioSession setActive:YES error: &error];
}
-(void) playAudio
{
NSLog(#"%s", __FUNCTION__);
if (audioPlayer.playing) {
[audioPlayer stop];
}
if (toggle == NO)
{
recordButton.enabled = NO;
if (audioPlayer)
[audioPlayer release];
NSError *error;
// GET THE APPROPRIATE SOUND FILE NAME
.....
//CHECK FOR EXISTING SOUNDFILE
if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
{
UIAlertView *someError = [[UIAlertView alloc] initWithTitle: #"Oops!" message: #"There is not a sound for this word. Press REC to record one. Press cancel to stop" delegate: self
cancelButtonTitle: #"REC" otherButtonTitles:#"CANCEL", nil];
[someError show];
[someError release];
}
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof (doChangeDefaultRoute),
&doChangeDefaultRoute
);
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:soundFileURL
error:&error];
audioPlayer.volume = 1.0;
audioPlayer.delegate = self;
if (error){
NSLog(#"Error: %#",
[error localizedDescription]);
}
else
{
[audioPlayer play];
}
}
recordButton.enabled = YES;
//NSLog(#"end of playAudio");
}
I've seen these warnings before, what happens is you copied another older project? if so this is what i did, I simply created a new blank project with the newest version of Xcode, and then started copying the old files into it.
this seemed to clear out those errors.

Resources