initWithData does not convert my data object into a string properly. When I check the length of the data object, it has a value.
NSMutableData* receivedData =[[NSMutableData data] retain];
NSString* json_string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
Am I doing something wrong creating the string?
As posted, the code is nonsense. You are creating an empty immutable data and then trying to create a string from said empty data.
What does * When I check the length of the data object, it has a value* mean? Do you mean that you have more code that you aren't showing? Something that is filling the mutable data with some bytes?
Also, if the received data is not actually encoded as a UTF-8 string, the conversion will fail. There are a number of methods on NSString that allow for lossy conversion. Try one of those.
I didn't fully complete the NSURLConnection delegate methods. This is where my data is being built.
Related
I'm creating a iphone clients that talks to a wcf service (I do not have control over the server, so no changes can be made here).
I need to send an image to this server, along with some other information. It must be send using json.
I'm using restkit to send and receive data.
The problem is, that the binary data must be send as a byte array. Not as a base64 encoded string.
How do I get from an UIimage to a json string that looks like this
"Picture":{"Content":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,..........
I'm open to a solution that doesn't use restkit.
What is the type in the receiving WCF service? byte[]?
Sounds hokey, but you could try mapping to an NSNumber realtionship and creating an array of them.
Off the top of my head I think that's going to serialize as:
"Picture":{"Content":["1","1","1".....
So you also might need a custom formatter.
Here's a SO post converting a byte array into an NSString. If i'm understanding the issue correctly try converting your byte array into the string then adding that to your feed.
Objective-C - How can I convert Byte Array to NSString?
Here's an excerpt of the accepted answer with code:
NSData *data = [[NSMutableData alloc] init];
uint8_t buffer[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buffer maxLength:1024];
if(len > 0)
{
[data appendBytes:&buffer length:len];
}
NSString *serverText = [[NSString alloc]
initWithData:data
encoding:NSASCIIStringEncoding];
NSLog(#"%#", serverText);
Also worth noting once you get the value into your json, watch out that you don't exceed your json max string length value.
Thanks for the quick replys.
Couldn't get any of the suggested answers to work, so we had to use our mad people skills and make the company who made the server side service change their end so we instead can send a base64 encoded string.
I'd like to copy a float into the pasteboard, but the important thing is the value, as I want to paste it later in numbers, as a number.
Tried with :
[pasteboard setValue:SomeNSNumberWhereIStoredTheFloat forPasteboardType:#"NSNumber"];
With that, it got nothing to paste, and with pasteboard.string = numberInStringValue, it pastes the number as a series of characters, in what I'm not interested.
Thanks for your help
The "type" of pasteboard data is not the name of a class, it's a Uniform Type Identifier (UTI, or just UT if you remember what else UTI stands for.) In this case, your data does not have an associated UTI (numbers are abstract concepts, not data formats.) You'll have to figure out the best way to store that number and retrieve it.
I think in this case, formatting the number into a string will suffice:
NSString *numString = [NSString stringWithFormat:#"%f", theFloatValue];
pasteboard.string = numString;
And later, when getting it back:
float theFloatValue2 = [pasteboard.string doubleValue];
This does not take into account checking for nil or other error handling.
If you need very high precision, you may need to investigate an NSData-based storage technique.
You can store an NSNumber directly. You can used the following methods from the API
setValue:forPasteboardType:
Use this method to put an object on the pasteboard that is a standard property-list object that is an object of the NSString, NSArray, NSDictionary, NSDate, NSNumber, or NSURL class.
valueForPasteboardType:
This method attempts to return an object that is of a class type appropriate to the representation type, which typically is a UTI. For example, if the representation type is kUTTypePlainText (public.plain-text), the method returns an NSString object. If the method cannot determine the class type from the representation type, it returns the object as a generic property-list object. Property-list objects include NSString, NSArray, NSDictionary, NSDate, or NSNumber objects, with NSURL objects also as a possibility. If the method cannot decode the value as a property-list object, it returns the pasteboard item as an NSData object.
The real problem comes in finding the correct UTI so the class will automatically give you back an NSNumber and not give you back an NSData object instead.
To make matters worse, the code doest not appear to work as the advertised by the documentation. I've heard from several people the method will always return you NSData. You can find an example (and a workaround) of such issue in this answer.
You can store your float value as NSNumber.
But NSNumber is not stored in UIPasteboard correctly although docs states it does (bug?).
To keep NSNumber in UIPasteboard you should archive NSNumber to NSData, and to retrieve NSNumber from UIPasteboard you should unarchive NSData back to NSNumber.
// adding data to pasteboard
NSNumber *number = [NSNumber numberWithDouble:floatValue]; // store your value here
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:number]; // archive NSNumber to NSData
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:data, #"yourKey",nil];
[[UIPasteboard generalPasteboard] addItems:[NSArray arrayWithObject:dict]];
// retrieving data
NSData *data = [dict valueForKey:#"yourKey"]; // here dict is properly obtained NSDictionary of pasteboard object
NSNumber *number = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // unarchive NSData to NSNumber
I'm working on writing to a file one user input on a textField.
So far I have one NSFileManager which writes data to a file. Still, I have no way of putting the textField input inside a file.
Is there a way do add a string value to NSData so I can write it?
you can get NSData from NSString,
NSData *newData = [yourString dataUsingEncoding:NSUTF16StringEncoding];
use encoding that fits your case.
append the obtained data to existing NSData,
[existingData appendData:newData]
Note: "existingData" should be an instance of NSMutableData.
Use below code as your reference.
NSString* myString = #"Is there a method for adding one NSString for NSData";
NSData* myData= [myString dataUsingEncoding:NSUTF8StringEncoding];
I'm getting garbage values when manipulating some of my NSString objects. I think the problem stems from my misunderstanding of how NSString works at a basic level. Below, I have a object which has a string pointer as a synthesized property. When I try to log it out directly, the compiler gives me a warning, but it does log out the value I expect. On the very next line, I try to log that string out the proper way but I end up getting garbage.
Code snippet
MyObject *object = [self.objects objectAtIndex:indexPath.row];
NSString *myString = object.myString;
NSLog(myString); // format not a string literal and no formal arguments
NSLog(#"formatted = %s", myString);
Output
2011-05-16 13:06:51.137 MyProgram[917:207] thisValueIsGood
2011-05-16 13:06:51.138 MyProgram[917:207] formatted = `å
This problem has snowballed onto other functions which use this final string. When I concatenate that string with other strings, I get even more garbage.
NSString is an object, instead of %s, use %#.
URL Download
http://code.google.com/p/mwiphonesdk/source/browse/#svn/trunk/iMADE/PrepTasks/08
I have code at the location at the link above and I am using NSMutableString to append strings as data is downloaded. But I am finding that using appendString does not increase the length of the mutable string. I must be doing something wrong.
And when I am done I need to convert NSMutableString to NSString to return it. I have looked for examples to do this but I do not see any yet.
I am most familiar with Java and C# where there is a StringBuffer/StringBuilder which allows you to append pieces and them simply call toString at the end to get a String. It does not appear to be this easy in Objective-C.
NSString* str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
#pragma mark TODO Confirm this is appending a value to the mutable string
[self.mutableString appendString:str];
NSLog(#"str length: %d, %d", [str length], [self.mutableString length]);
Above is the section of code that calls appendString.
I see that str has a length > 0 but calling appendString does not increase the length of self.mutableString.
What am I doing wrong here?
As for having an NSMutableString* and needing to return an NSString*, the former is a subclass of the latter so anywhere you see an NSString* an NSMutableString* will suffice as-is.
Your code looks OK from what you've posted. The only thing I can think of is that perhaps there isn't any data to speak of when initializing the str variable. In such a case appending an empty string will do nothing to mutableString.
You'll also want to make sure self.mutableString has been properly allocated and initialized. You can send messages to NSObject*s that are nil which may be misleading when [self.mutableString length] returns 0.
I have fixed the problem. I simply was not initializing the NSMutableString value and it was transparently not doing anything.
Before appending the string I put the following code.
if (_mutableString == nil){
_mutableString = [[NSMutableString alloc] init];
}
Thanks everyone for answering. And it is good to know that I can use NSMutableString in place of NSString. (that is too easy) :)