how to pass image to a web service in string format from xcode - webservice-client

+(id)profilePictureUploadWebService :(NSString*)temp andimage:(NSString*)strimage
{
//NSString *post=[NSString stringWithFormat:#"_UserId=%#&_UserImage=%#",temp,strimage];
NSString *post=#"";
NSString *urlTotal= [ NSString stringWithFormat:#"http://mo.sale.com/as.asmx/SaveUserImage?_UserId=%#&_UserImage=%#",temp,strimage];
NSURL *url= [ NSURL URLWithString:urlTotal];
NSLog(#"urlTotal is =%#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data is =%#",data);
return (urlData);
}

Related

How to create sqlite custom file in ios?

I am working on application where using local database as sqlite.
Where I want to create custom file for sqlite I don't know how to do this.
Any help would be appreciated.
First of all add below file into your project.
https://github.com/ConnorD/simple-sqlite
Then create database.sqlite file into your project. Database contain user first nam,last name and profile picutre.
And add below code into your AppDelegate file.
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"testing" message:#"path for database" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
// [alert release];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
//NSLog(#"Default writableDBPath: %#",writableDBPath);
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Category_DB.sqlite"];
//NSLog(#"Default : %#",defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// NSLog(#"Success");
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Call this method into your didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createEditableCopyOfDatabaseIfNeeded];
return NO;
}
Now write below code into your view controller where you want to use queries.
-(void)databaseOpen
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
myDatabase = [[Sqlite alloc] init];
[myDatabase open:myDBnew];
// NSLog(#"database opened");
}
For select query:
[self databaseOpen];
NSString *query_fetch=[NSString stringWithFormat:#"select Max(session_id) from Report"];
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
IF you want to save image to database
-(NSString *) getImagePath{
/* *** Modify on 16 01 2012 by Prerak *** */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
return documentsDirectory;
}
IF you want to get image to database
arrProfilepic = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath error:&error];
NSLog(#"File Path Array is %#",filePathsArray);
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingString:#"/"] stringByAppendingString:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
//NSLog(#"Data %#", data);
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"Image %#", image);
[arrProfilepic addObject:image];
}
}
}
NSLog(#"profile is %#",arrProfilepic);
For Insert query:
NSString *documentsDirectory = [self getImagePath];//save image to database
NSString *imagePath;
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"User_%d.png",newid]];
NSString *relativePathImage1=nil;
NSArray *relativeArray=[imagePath componentsSeparatedByString:#"/Documents"];
UIImage *thumbImage;
thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)];
NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f);
[thumbData writeToFile:imagePath atomically:YES];
NSString *query_insert=[NSString stringWithFormat:#"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%#','Smith','%#')",newid,VcAddUser.txtFUsername.text,relativePathImage1];
NSMutableArray *userData=[[NSMutableArray alloc]init];
userData=[[myDatabase executeQuery:query_insert];
[database close];
For Delete query:
NSString *query_user=[NSString stringWithFormat:#" delete from UserDetails where User_id=%d",Userid];
[myDatabase executeNonQuery:query_user];
[myDatabase close];
**For Update query:**
NSString *updatequery=[NSString stringWithFormat:#"Update UserDetails set User_fname='%#',User_lname='%#', User_image='%#' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate];
[myDatabase executeNonQuery:updatequery];
// NSLog(#"Query user is %#",updatequery);
[myDatabase close];
For Webservices
-(void) CallWebservice
{
NSMutableData *responseData = [NSMutableData data];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"give your web service url"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self removeProgressIndicator];
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// check for response only
/*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);*/
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}

how to add values from nsstrings in iOS?

I have 5 buttons. Each button has some value like 1,2,3,4,5 in a string named totalSeats_selected.
I want to save them into a nsstringthat shows result like this:
nsstring * result = [1,2,3,4,5];
These values are to used as request for a web service, so it must be in this format to send total number of seats?
So, how to save all these values in nsstring on button event?
Use like this.Suppose your string is in integer means use Method 1 .otherwise use Method 2(If your value assigned in NSString).
Method 1:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setValue:[NSNumber numberWithInt:[first intValue]] forKey:#"1"];
[datadict setValue:[NSNumber numberWithInt:[second intValue]] forKey:#"2"];
[datadict setValue:[NSNumber numberWithInt:[third intValue]] forKey:#"3"];
[datadict setValue:[NSNumber numberWithInt:[fourth intValue]] forKey:#"4"];
[datadict setValue:[NSNumber numberWithInt:[fifth intValue]] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}
Method 2:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setObject:[NSString stringWithFormat:#"%#",FIRST] forKey:#"1"];
[datadict setObject:[NSString stringWithFormat:#"%#",SECOND] forKey:#"2"];
[datadict setObject:[NSString stringWithFormat:#"%#",THIRD] forKey:#"3"];
[datadict setObject:[NSString stringWithFormat:#"%#",FOURTH] forKey:#"4"];
[datadict setObject:[NSString stringWithFormat:#"%#",FIFTH] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}

how to send a parameter from iOS to ASP.NET WebService?

i have a web service, written in c# which look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloParam(string param)
{
return "Hello " + param;
}
my code in Xcode look like this:
- (IBAction)getButton:(id)sender {
NSString *urlString = #"http://172.16.43.132/Server/Service1.asmx/HelloParam";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"Shit");
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
}
when i call the method hello world. i receive an answer in xml format. it should be in json.
when i call the second method "helloparam" i get an error: parameter is missing.
could you give me a simple example of how to create a connection and communication between an iPhone and a asp.net web service? thanks in advance

Using asmx file for uploading image from iphone

Im struggling here for a lot,
Im trying to upload an image from iphone to (iis)server folder using webservice asmx(VB.net)
Ive searched a lot and finally used the following code
- (IBAction)btnPostImages_Clicked:(id)sender {
NSMutableURLRequest *request;
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"http://192.168.0.2/digita/digitacampus.asmx/SaveImage"]];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n",#"recFile",#"image.jpg"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dt]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
dt is NSData of image in jpeg representation
and the webmethod as follows
<WebMethod()> _
Public Function SaveImage(ByVal recFile As String) As String
Dim file As HttpPostedFile = HttpContext.Current.Request.Files("recFile")
Dim targetFilePath As String = HttpContext.Current.Server.MapPath("") + file.FileName
file.SaveAs(targetFilePath)
Return file.FileName.ToString()
End Function
Nothing happened
Is the above webmethod correct
I have also tried simply as below
- (IBAction)btnPostImages_Clicked:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://192.168.0.2/digita/digitacampus.asmx/SaveImage"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:dt];
NSURL *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}
I dont know what to do else
whats the mistake that I did
How can I identify the image was successfully uploaded or not
Is the URL correct? I think it should be something like: digitacampus.asmx?op=SaveImage and maybe digitalcampus.asmx
You have to convert the String to an filestream like this for example:
Dim fs As FileStream
fs.Write(System.Convert.FromBase64String(recFile), 0, pdfLength)

converting NSString to NSURL from a plist file

I've been trying to get a string from a plist file into a NSURL for webview.
Either i get 'nil' for the returned value, or nothing (no error in console)
I know something's wrong with this code, but i can't pinpoint it where.
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *value;
value = [plistDict objectForKey:#"Link"];
NSString *webStringURL = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:webStringURL];
[self loadURL:URL];
[self setURLToLoad:nil];
Where did i mess up?
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *urlString = [plistDict objectForKey:#"Link"];
NSURL *URL = [NSURL URLWithString:urlString];
[self loadURL:URL];
For your better understanding refer to this site:
http://iphonesdevsdk.blogspot.com/2011/04/plist.html
It may help you in using plist in easy way.

Resources