Cocoa POST issue - cocoa

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.

Related

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

Compilation fails due to prototype cell

I have a TableViewController subclass with one prototype cell designed in storyboard. Then I am passing the references to the class header etc and for some reason it fails to compile it. But the connections seem fine. I provide you the code and pictures of the build errors and the storyboard. I am using Xcode 4.3.3. Any help is really appreciated.
favTable.h
#import <UIKit/UIKit.h>
#interface favTable : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
NSArray *favArr;
NSMutableArray *favName;
NSMutableArray *favScore;
}
#property (nonatomic, retain) NSArray *favArr;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSMutableArray *favName;
#property (nonatomic, strong) NSMutableArray *favScore;
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) IBOutlet UITableViewCell *celldes;
#property (strong, nonatomic) IBOutlet UIImageView *cellimage;
#property (strong, nonatomic) IBOutlet UILabel *cellname;
#property (strong, nonatomic) IBOutlet UILabel *cellmanu;
#property (strong, nonatomic) IBOutlet UILabel *cellscore;
#end
favTable.m
#import "favTable.h"
#import "ecoAppDelegate.h"
#interface favTable ()
#end
#implementation favTable
#synthesize favArr;
#synthesize managedObjectContext;
#synthesize fetchedResultsController;
#synthesize favName;
#synthesize favScore;
#synthesize celldes;
#synthesize cellimage;
#synthesize cellname;
#synthesize cellmanu;
#synthesize cellscore;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Favorites";
self.navigationController.navigationBar.translucent = NO;
// passing the array of addedtofavorites to the total one with all favorites
self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"FavoritesInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.resultType = NSDictionaryResultType;
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:#"name", nil]];
NSError *error=nil;
self.favArr=[[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]mutableCopy];
if (error!=nil) {
NSLog(#" fetchError=%#,details=%#",error,error.userInfo);
}
self.favName = [[self.favArr valueForKey:#"name"] mutableCopy];
self.favScore = [[self.favArr valueForKey:#"score"] mutableCopy];
}
- (void)viewDidUnload
{
[self setCelldes:nil];
[self setCellimage:nil];
[self setCellname:nil];
[self setCellmanu:nil];
[self setCellscore:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [favName count];;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
// Configure the cell...
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cellname.text = #"Test";
return cell;
}
#end
I moved manually the IB outlets into a separate custom cell class and then linked the references to the storyboard (maybe this is fixed in newer versions)
Then applied that cell style in the prototype cell and simply changed the content of the UI items of my cell using the identifier (no tag was needed)

Adding objects to array NSXMlParser no data

I'm trying to make a XML-parser that saves data from YR.no-API. The parser should add data to these two datastructures. My problem is when i try to add a WeatherTimeData object to my array in WeatherData, it seems like the objects doesnt get added, the following count always give me zero
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:#"time"])
{
[self.weatherdata.timedata addObject:currentWeatherTimeData];
NSLog(#"amount of objects in timedata-array %d", [[self.weatherdata timedata] count]);
}
These are my two data-structures, i alloc weatherData in the following method
-(id) loadXMLByURL:(NSString *)urlString
{
_weatherdata = [[WeatherData alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
Do i have to alloc the array inside of the weatherdata object?
WeatherData.h
#interface WeatherData : NSObject
#property (strong, nonatomic)NSString *town;
#property (strong, nonatomic)NSString *country;
#property (strong, nonatomic)NSMutableArray *timedata;
#end
WeatherData.m
#implementation WeatherData
#synthesize town = _town;
#synthesize country = _country;
#synthesize timedata = _timedata;
#end
WeatherTimeData.h
#interface WeatherTimeData : NSObject
#property (strong, nonatomic)NSDate *startTime;
#property (strong, nonatomic)NSDate *endTime;
#property (strong, nonatomic)NSString *iconSymbol;
#property (strong, nonatomic)NSString *windDirection;
#property (strong, nonatomic)NSString *windSpeed;
#property (strong, nonatomic)NSString *temprature;
#property (strong, nonatomic)NSString *preassure;
#end
WeatherTimeData.m
#implementation WeatherTimeData
#synthesize startTime = _startTime;
#synthesize endTime = _endTime;
#synthesize iconSymbol = _iconSymbol;
#synthesize windDirection = _windDirection;
#synthesize windSpeed = _windSPeed;
#synthesize temprature = _temprature;
#synthesize preassure = _preassure;
#end
This type of problem is classically because the object hasn't been allocated, and given Objective-C allows messages to be sent to nil the programmer doesn't notice.
I think it would be nice to be able to provide a runtime environment variable where such events are logged to stdout...
I would suspect that [WeatherTimeData init] isn't creating timedata and that's because you haven't provided an implementation for it; just using #sythensize isn't enough to create the objects.

xcode textfield to NSURL path

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

NSAttributedString as a Transformable Attribute in Core Data Entity

In the Core Data Programming Guide under "Transformable Attributes" here.
It is stated "You can now use the attribute as you would any other standard attribute, as illustrated in the following code fragment:"
The follow line of code is listed newEmployee.favoriteColor = [NSColor redColor];
I am trying to do something similar in my code but it doesn't work. Here is my code:
In Entry.h:
#interface Entry : NSManagedObject
{
}
#property (nonatomic, retain) NSAttributedString * contentString;
#property (nonatomic, retain) NSDate * date;
#property (nonatomic, retain) NSManagedObject * journal;
#end
and in Entry.m:
#implementation Entry
#dynamic contentString;
#dynamic date;
#dynamic journal;
- (void)awakeFromInsert {
[super awakeFromInsert];
self.date = [NSDate date];
}
#end
Elsewhere I have this code:
Entry *newEntry =
[NSEntityDescription insertNewObjectForEntityForName:#"Entry"
inManagedObjectContext:[self managedObjectContext]];
newEntry.contentString = [[[NSAttributedString alloc] initWithString:#"MyString"] autorelease];
newEntry.journal = self.journal;
The line
newEntry.contentString = [[[NSAttributedString alloc] initWithString:#"MyString"] autorelease];
is equivalent to
newEmployee.favoriteColor = [NSColor redColor];
As far as I can tell however this doesn't work. I get a runtime error:
2010-10-13 09:02:08.577 JournalMaker[2437:a0f] Cannot create NSData
from object MyString{ } of class NSConcreteAttributedString
I have no idea what this error message is supposed to mean. Can someone explain?

Resources