How to send a Message from iPhone to Windows? - iphone

I have an object with the following members:
NSString *reqStr = "param1=val1&param2=val2&param3=val3&..";
NSData *imageData = [NSJPEGRepresentation (myimage)];
NSData *fileContents = [NSData initWithFileContents(myfile.txt)];
How can I send this out to Windows WCF? Do I send it as stream of bytes, and attach to httprequest? Or, will this be sockets? I am not sure how to pack these things as one thing as in one stream of bytes or whatever it may be the way to format such an object.
Any help?

Since you said that you already know how to send imageData which is NSData. Why not convert regStr to NSData and combine all three together as a single data and send.
To convert NSString to NSData:
NSData* strData=[regStr dataUsingEncoding:NSUTF8StringEncoding];
And use NSMutableData's appendData method to combine all three.
NSMutableData *combineData = [[NSMutableData alloc]initWithData:strData];
[combineData appendData:imageData];
[combineData appendData:fileData];

This S/O question might help:
File Upload to HTTP server in iphone programming
If the WCF endpoint is configured as HTTP then the same principles should apply regarding the multipart/formencoding of the image in question.
Edit:
Is this answer more helpful ?
HTTP "POST" request in iOS

Related

How to store NSData from NSURLConnection sendSynchronousRequest as a pdf file to documents directory in iOS?

I am getting the NSData using
NSData * responseData = [NSURLConnection sendSynchronousRequest:mutableUrlRequest returningResponse:nil error:nil];
How to store this as a PDF to local documents directory? My service is in java which returns byte array.
Thanks !
try like this
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[data writeToFile:[docPath stringByAppendingPathComponent:#"name.pdf"]
atomically:YES];
You really need to confirm that your request has been successful:
Provide a pointer for the response which on return contains the status code and the MIME type of the response data, possibly also content length and other useful info. Check against what you expect.
Provide a NSError pointer, too in order to get the error when the connection fails (returns nil).
That's what you should always do when you make a toy app. When you make a more serious app, you should use the asynchronous style to perform a network request. Basically, you implement the two NSURLConnection Delegate protocols. There is lot of info already in SO how to accomplish this, and as well in Apple samples. If you have any specific questions, please ask again :)
How to store this as a PDF to local documents directory?
This question has been answered already.

NSMutableURLRequest sends partial post body

I'm sending a base64 encoded image to a server as part of a post request using NSMutableURLRequest. What I log as the post body and what the server receives are not the same thing. The server seems to get a truncated version, as though the connection aborts midway. See the code below:
NSString *dataStr = [NSString stringWithFormat:#"request_data=%#",reqStr];
NSLog(#"datastr is %#",dataStr);
NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"nsdata length is: %i",[dataForUrl length]);
[urlRequest setHTTPBody:dataForUrl];
[urlRequest setValue:[NSString stringWithFormat:#"%d", [dataForUrl length]] forHTTPHeaderField:#"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *res, NSData *data, NSError *err) {
// ...
}
The first log statement shows the correct data. I even took the base64 part of the string to http://www.motobit.com/util/base64-decoder-encoder.asp, decoded it as a jpg, and it is the correct image. The second log statement shows that the length is the right size (422624 when the picture was 422480, for example).
I can't find anything wrong with the connection details or the data. The phone makes the connection, sends some data, then either the phone stops sending or the server stops receiving. What could cause that?
Edit: link to sample data http://pastebin.com/BS9HjKhg
Edit2: The server or iOS is converting the +'s from the image to spaces. I'll post an answer when I figure out the right way to send it.
I was able to compare a full sample from the server vs what xcode logged, and found the + converted to [space]. Since that was the only character having a problem and url encoding is buggy in iOS, I just did
NSString *dataStr = [NSString stringWithFormat:#"request_data=%#",[reqStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"]];
The server is accepting them again. I'm still not sure whether the server was the problem or it was iOS. The other OS's that connect use the same application/x-www-form-urlencoded as their content type with no problems.
I would suggest doing the conversion from Base64 string into NSData through Nick Lockwood's Base64 class.
That
NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
worries me a bit (even more after looking at how Base64 is implements the conversion)...

How to submit a very-very long String to server via POST and get jSON response

I wish to send a very very long string(length of string is more than 10000) to the server and in return get the jSON response from the string.What is the best approach for the task. I am sending various parameters along with this very very long string.
Split down your long string to parts which can be send over one request. Create a json like this
{
"index":"0",
"length":"LENGTH_OF_STRING",
"string":"xsfsffwff.......",
//other json parameters
}
then you can send your string
The problem is that you're trying to put this all into a query parameter. Most servers have built-in limits for URLs, and for good reason.
There's nothing special about the body of an HTTP POST, so just send that up like you would anything else. Just make sure that you set the Content-Length header (since you know that; it might be covered by the HTTP library) and then just stream your data up. No need for any encoding or query params.
I don't know much about objective-c, but I'm sure there's a way to send data like this in an HTTP POST very simply. I've done this with Go and node.js, and both have simple ways of sending arbitrary data in a POST request body.
If you are using the ASI-Http classes , then you can send request like this
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[WebService getAddPhoto]]];
[request addPostValue:[[imgArray objectAtIndex:i] valueForKey:#"vComments"] forKey:#"comment"];
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:[[imgArray objectAtIndex:i] valueForKey:#"vPhoto"]]);
NSString *encodedString = [imageData base64EncodingWithLineLength:[imageData length]];
[request addPostValue:encodedString forKey:#"Photo"];
[request setDelegate:self];
[request startAsynchronous]

iPhone NSURLConnection: What to do with returned NSData Object? Google Docs API

I'm working with the Google Docs API in my iPhone application. I've sent the proper POST request, and received a response along with some NSData. If I NSLog the NSData object, I get this:
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:theResponse error:NULL];
NSLog(#"%#",returnedData);
//output : <4572726f 723d4261 64417574 68656e74 69636174 696f6e0a>
I think the NSData is either an NSDictionary or an NSArray. I'm supposed to receive a couple of items back, an SID, an LSID, and an Auth.
If I could turn the NSData chunk into an NSDictionary I could just find the object for whichever key.
Can anyone help?
You will have to decode the data. Try the following:
NSString *result= [[NSString alloc] initWithData:returnedData encoding:NSASCIIStringEncoding];
Of course this will depend on how the data is encoded. NSUTF8StringEncoding might work instead.
You may just need to pass the data to an NSXMLParser
The best way to deal with web data is Doing NSXML parsing. No need of decoding data the parser will handle itself

Retrieving images to iphone app through XML

I have made an iphone application in which data is retrieved from remote server through xml saved. I want to retrieve images also with in the XMl and have to show them in my iphone application stored on server. Please help how this can be achieved.
In my application I am both sending and receiving images through Xml. In order to facilitate this, I encode/decode the images using base64 encoding. MY encode/decode methods live in 2 objective-c categories, 1 for NSData and 1 for NSString. You call these methods on the respective data types, I have listed examples below. The methods are [NSData base64Encoding] and [NSString base64Decoding].
When sending to the server...
NSLog(#"Compressing Image: JPEG 80%");
NSData *imgData = UIImageJPEGRepresentation(scaledImage, 0.8f);
NSString *b64String = [imgData base64Encoding];
My "b64String" variable now has a base64 encoded string representation of my image. You can now wrap this in Xml and use your normal NSURLConnection to send it to the server.
When receiving from the sever... (Make sure you are sending base64 encoded text from the server)
You will do your normal Xml parsing, here my "value" variable holds the base64 string from the server.
NSData *imgData = [value base64Decoding];
UIImage *image = [[UIImage alloc] initWithData:imgData];
You should be able to look up some common base64 encoding/decoding algorithms in Objective-C, let me know if you would like me to post my methods (they are kinda long so I obmitted them here).
I'm writing an app at the moment that has this problem - I've solved it by putting a url to the image in the xml instead of embedding the image data itself. For example my xml looks something like this :
<images>
<image url="http://www.example.com/images/12345.jpg" />
<image url="http://www.example.com/images/67890.jpg" />
</images>
As I'm parsing the xml, when I hit an < image > tag I store the url in an NSMutalbeArray. When the xml is parsed I loop through the array and get each image using NSURLConnection.
Sam
PS I worked out how to use NSURLConnection from this page : https://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html