ASIFormDataRequest post type - web-services

I need to send RestFul Web Service Request with post type ,post data format is like as below {"Request":"parameters".... }and binary data with same request.Is it possible with ios if possible means explain please?

I don't recommend using the ASIHttpRequest library anymore because it's not getting any updates from the developer , as to how to create a post http request here's an example
NSString *url = #"your webservice base url";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *param2 = ...//
NSData *binaryData = .... //initilize the binary data you want to send
NSString *bodyString = [NSString stringWithFormat:#"param1=%#&param2=%#",binartData,param2];
[request setValue:[NSString stringWithFormat:#"%d", [bodyString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSASCIIStringEncoding]];//or set the type of encoding agreed with your webservice
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString;
if ( responseData && !error){
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}

Related

How to translate the object c into rubymotion to fetch facebook user’s information

I tried to translate part of the objective-c but I still stuck at part of them
any idea ? Thanks so much
objective c version
if ([FBSDKAccessToken currentAccessToken]) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture",#"fields",nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
UIImage * downloadedImage = [UIImage imageWithData:pictureData];
dispatch_async(dispatch_get_main_queue(), ^{
self.profilePictureImageView.image = downloadedImage;
});
}];
}
ruby motion version
if (FBSDKAccessToken.currentAccessToken) {
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
}
Finally, I came up with the corresponding code in rubymotion
Please correct me directly if anything wrong, it works for me now
part of original objective-c
if ([FBSDKAccessToken currentAccessToken]) {
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
}];
}
convert version by ruby_motion_query
def loginButton(loginButton, didCompleteWithResult: result, error: error)
puts result
puts error
if not error
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
request.startWithCompletionHandler( lambda{ |connection, user, error|
#DO_ANYTHING_YOU_WANT_FATE_LOGINING_SUCESSFULLY
rmq(#fb_login_button).animate { |btn| btn.move(b: 400) }
#name_label = rmq.append(UILabel, :label_name).get
#name_label.text = "#{user['first_name']} #{user['last_name']}"
rmq(#name_label).animations.fade_in
})
end
end
def loginButtonDidLogOut(loginButton)
#DO_ANYTHING_YOU_WANT_HERE
end

NSData dataWithContentsOfURL returns nil

I am trying to fetch a XML file from a URL and store it locally, yet I find the [NSData dataWithContentsOfURL xxxx] returns nil to me.
The error message reads: operation couldn’t be completed. (Cocoa error 256.)
Could you help to review my code and point to me the problem:
NSError* err = nil;
NSString* urlString = #"http://www.w3school.com.cn/example/xmle/note.xml";
NSURL* xmlUrl = [NSURL URLWithString:urlString];
NSData* xmlData = [NSData dataWithContentsOfURL:xmlUrl options: NSDataReadingUncached error: &err];

Uploading multiple binary items as part of a batch call on iOS

I'm trying to make post with more than a photo in Fb using batch request but I keep getting timeout errors from Fb server...
This is my code ..
UIImage *imgFile1 = [UIImage imageNamed:#"iTGps.png"];
NSData *imageData = UIImageJPEGRepresentation(imgFile1, 0.5);
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\",\"body\":\"message=My cat photo\",\"attached_files\":\"%#\"}",imageData];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#,%#,%#]",jsP1,jsP1,jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
FBRequestConnection *connect = [[FBRequestConnection alloc] initWithTimeout:60];
// do Fb request
FBRequest *request = [FBRequest requestWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"];
// add connection
[connect addRequest:request
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"Result:%#,%#",result,error);
}];
[connect start];
Where am I doing wrong??
Error code is very long so i cut the middle part (i think is the binary images)
2013-04-28 20:03:32.435 trueGps[1887:1a603] Result:(null),Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x14454010 {com.facebook.sdk:ErrorInnerErrorKey=Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14492d40 {NSErrorFailingURLStringKey=https://graph.facebook.com/me/photos?sdk=ios&batch=%5B%7B%20%22method%22%3A%20%22POST%22%2C%20%22relative_url%22%3A%20%22me%2Fphotos%22%2C%22body%22%3A%22message%3DMy%20cat%20photo%22%2C%22attached_files ....
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x2a90f620 "The request timed out."}, com.facebook.sdk:HTTPStatusCode=200}
i solve the problem .. but still have more post with only a photo in every one..
NSString *rel_url = [NSString stringWithFormat:#"%#/photos",nomeAlbum];
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"body\": \"message=My_cat_photo\", \"attached_files\": \"file1\" }",rel_url];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#]",jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
[params setObject:imgFile1 forKey:#"file1"];
[FBRequestConnection startWithGraphPath:rel_url
parameters:postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
}];

Cannot access web service in iOS

I want to connect with a web service from my iOS app. Previously my URL was http://<domain name>/mobilews/mobilews.asmx. Recently I changed to http://<domain name>/mobilewstest/mobilews.asmx
I have put my URL in info plist file. But after I changed this into new URL I cannot login to that.
NSString *urlString = [NSString stringWithFormat:#"%#%#",serverURL,[queryString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse *response ;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
int statusCode = [((NSHTTPURLResponse *)response) statusCode];`
Here returnData become nill and statusCode is 0. But this urlString is successfully logged in to the web service when it gives in the browser.
NSURL *url = [NSURL URLWithString:#"YOUR URL HERE"];
NSError *connectionError = nil;
NSData *inData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&connectionError];
NSInteger code = [connectionError code];
if (code != 0)
{
NSString *locDesc = [NSString stringWithString:[connectionError localizedDescription]];
NSString *locFail = [NSString stringWithString:[connectionError localizedFailureReason]];
NSLog(#"Error: %d %# %#", code, locDesc, locFail);
}
else if ([inData length] == 0)
{
NSLog(#"No data");
}
else{
NSData *resultData = [NSData dataWithContentsOfURL:url];
NSString *responseString = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
}
I see you send a syncronous request... try this its more an easy approach.

Adding downloaded NSImage into an NSArrayController - AWS iOS Asynchronous S3 S3GetObjectRequest

I have a NSTableview with three columns 'Thumbnail','FileName' and 'Datemodified'. The file name column and date modified column is filled with the output of S3ListObjectResponse. While the 'Thumbnail' column image is loaded from the local directory of the machine. If the file is missing, I download it from the S3 cloud. The problem is how to insert the data into the NSArrayController if the file is missing and I'm left with an empty cell for the thumbnail? Here is my work as of now :
- (IBAction)checkCloud:(id)sender {
AmazonS3Client *s3 = [AmazonClientManager s3];
S3ListObjectsRequest* listObjectsRequest = [[S3ListObjectsRequest alloc] initWithName:#"hello-testing"];
NSRange range = NSMakeRange(0, [[_fileListAC arrangedObjects] count]);
[_fileListAC removeObjectsAtArrangedObjectIndexes:[NSIndexSet indexSetWithIndexesInRange:range]];
#try {
S3ListObjectsResponse* response = [s3 listObjects:listObjectsRequest];
NSMutableArray* objectSummaries = response.listObjectsResult.objectSummaries;
//looping through the objSummary and add into the NSArrayController
for ( S3ObjectSummary* objSummary in objectSummaries ) {
NSImage *thumbnail = [[NSImage alloc] init ];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *s3date = [dateFormatter dateFromString:[objSummary lastModified]];
NSArray *fileName = [[objSummary key] componentsSeparatedByString:#"/"];
if([[fileName objectAtIndex:0] localizedCaseInsensitiveCompare:#"Range"] == NSOrderedSame) {
NSLog(#"file name %# ",[fileName objectAtIndex:1]);
// Check for files in side the bucket's folders
if([[fileName objectAtIndex:1] length]){
NSString *thumbnailFile = [[fileName objectAtIndex:1] stringByAppendingString:#"_thumb.png"];
BOOL isDir;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePathPart1 = [#"/Users/" stringByAppendingString:[[NSHost currentHost] localizedName]];
NSString *filePath = [[[[ filePathPart1 stringByAppendingString:#"/Documents/Test/" ] stringByAppendingString:#"Range" ] stringByAppendingString:#"/Thumbnail/"] stringByAppendingString:thumbnailFile];
// If file exists then add into the thumbnail column
if([fileManager fileExistsAtPath:filePath isDirectory:&isDir]){
thumbnail = [[NSImage alloc] initWithContentsOfFile:filePath];
}else{
NSLog(#"file %# not found",thumbnailFile);
//Downloading from the S3 Cloud Asynchronously
doneDownload = NO;
AmazonS3Client *s3 = [AmazonClientManager s3];
S3GetObjectRequest *gor = nil;
#try {
gor = [[S3GetObjectRequest alloc] initWithKey:[[#"Range/Thumbnail/" stringByAppendingString:[fileName objectAtIndex:1]] stringByAppendingString: #"_thumb"] withBucket:#"thumbnail-pic" ];
gor.delegate = self;
[s3 getObject:gor];
}
#catch (AmazonClientException *exception) {
doneDownload = YES;
}
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!doneDownload);
gor.delegate = nil;
}
}else{
//If its the actual bucket folder and not file then load a default image
thumbnail = [NSImage imageNamed:#"Range.png"];
}
}
[_fileListAC addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:thumbnail,#"thumbnail", [objSummary key],#"Files",s3Date,#"Date Modified", nil]];
}
}
#catch (NSException *exception) {
NSLog(#"Cannot list S3 %#",exception);
}
//Display the table on loading the NSArrayController
[_cloudFileList makeKeyAndOrderFront:nil];
}
I have checked the delegate method
-(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response{
NSData *imageData = [response body];
_coreDataImageView.image = [[NSImage alloc] initWithData:imageData];
doneDownload = YES;
}
coredataimageview is a test image well. The image is downloaded but I want to add it back to the array controller. Issue is what if I have 3 file missing from the local directory and I'm unable to insert into array controller for that file name and date modified values. Any help on this?
If you implement a delegate object (rather than using self) you could store these objects in an array and reference them later. The delegate object could track the additional pieces of metadata you are interested in and could be used to construct your table view.