The back end developer had given these instructions in POST requests:
Having no experience with number 5 in the protocol, I searched and ended with my code.
-(id)initWithURLString:(NSString *)URLString withHTTPMEthod:(NSString *)method withHTTPBody:(NSDictionary *)body { _URLString = URLString; HTTPMethod = method; HTTPBody = body; //set error message errorMessage = @"Can't connect to server at this moment. Try again later"; errorTitle = @"Connection Error"; return self; } -(void)fireConnectionRequest { NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init]; [mainQueue setMaxConcurrentOperationCount:5]; NSError *error = Nil; NSURL *url = [NSURL URLWithString:_URLString]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; NSData *sendData = [NSJSONSerialization dataWithJSONObject:HTTPBody options:NSJSONWritingPrettyPrinted error:&error]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPBody: sendData]; [NSURLConnection connectionWithRequest:request delegate:self]; NSString *jsonString = [[NSString alloc]initWithData:sendData encoding:NSUTF8StringEncoding]; //fire URL connectiion request [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) { //get the return message and transform to dictionary NSString *data = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; returnMessage = [NSJSONSerialization JSONObjectWithData: [data dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error]; //check return message if (!error) { [delegate returnMessageForTag:self.tag]; } else { [delegate returnErrorMessageForTag:self.tag]; } }]; }
I pass a dictionary formatted to JSON. he agrees that I was able to pass the right data. And I was able to connect to the API, but it is always returning "FAILED" when I try send data for registration. There are no problems in connection, but I failed to transfer the data.
The android developer here using the same API has no problem with it, but wasn't able to help me out since he's not familiar with iOS.
What am I missing?
setRequestMethod("POST"); connection. setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection. setRequestProperty("Content-Length", "" + Integer. toString(urlParameters.
Hence, it is advised to use x-www-form-urlencoded when you have to send form data e.g. most of the web form which asks you to enter values and use multipart/form-data when you have to upload files to the server as used here.
The application/x-www-form-urlencoded content type describes form data that is sent in a single block in the HTTP message body. Unlike the query part of the URL in a GET request, the length of the data is unrestricted.
Try like this code
Objective C
NSString *post =[NSString stringWithFormat:@"AgencyId=1&UserId=1&Type=1&Date=%@&Time=%@&Coords=%@&Image=h32979`7~U@)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://google/places"]]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Swift 2.2
var post = "AgencyId=1&UserId=1&Type=1&Date=\(strDateLocal)&Time=\(strDateTime)&Coords=\(dict)&Image=h32979`7~U@)01123737373773&SeverityLevel=2" var postData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)! var postLength = "\(postData.length)" var request = NSMutableURLRequest() request.URL = NSURL(string: "http://google/places")! request.HTTPMethod = "POST" request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPBody = postData NSError * error NSURLResponse * response var urlData = try! NSURLConnection.sendSynchronousRequest(request, returningResponse: response)! var str = String(data: urlData, encoding: NSUTF8StringEncoding)
Swift 3.0
let jsonData = try? JSONSerialization.data(withJSONObject: kParameters) let url: URL = URL(string: "Add Your API URL HERE")! print(url) var request: URLRequest = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = jsonData request.setValue(Constant.UserDefaults.object(forKey: "Authorization") as! String?, forHTTPHeaderField: "Authorization") request.setValue(Constant.kAppContentType, forHTTPHeaderField: "Content-Type") request.setValue(Constant.UserAgentFormat(), forHTTPHeaderField: "User-Agent") let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if data != nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary print(json) } catch let error as NSError { print(error) } } else { let emptyDict = NSDictionary() } }) task.resume()
Swift 4
let headers = [ "Content-Type": "application/x-www-form-urlencoded" ] let postData = NSMutableData(data: "UserID=351".data(using: String.Encoding.utf8)!) let request = NSMutableURLRequest(url: NSURL(string: "Add Your URL Here")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error!) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse!) do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) print(json) } catch { print(error) } } }) dataTask.resume()
Alamofire
Alamofire.request("Add Your URL Here",method: .post, parameters: ["CategoryId": "15"]) .validate(contentType: ["application/x-www-form-urlencoded"]) .responseJSON { (response) in print(response.result.value) }
I hope this code useful for you.
Swift 4
let params = ["password":873311,"username":"jadon","client_id":"a793fb82-c978-11e9-a32f-2a2ae2dbcce4"] let jsonString = params.reduce("") { "\($0)\($1.0)=\($1.1)&" }.dropLast() let jsonData = jsonString.data(using: .utf8, allowLossyConversion: false)! urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type") urlRequest.httpBody = jsonData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With