I am trying to sent input from the user to a php script to have it ultimately passed to an SQL server, Most of the code runs but having problem with submitting the data.
#IBAction func submit(_ sender: AnyObject) {
let requestURL = URL(string: "*****")
let request = NSMutableURLRequest(url:requestURL!)
request.httpMethod = "POST"
let song=txt1.text!
let artist=txt2.text!
let album=txt3.text!
let year=txt4.text!
let genre=txt5.text!
let songPost = "song=" + (song as String)
let artistPost = "&artist=" + (artist as String)
let albumPost = "&album=" + (album as String)
let yearPost = "&year=" + (year as String)
let genrePost = "&genre=" + (genre as String)
request.httpBody = songPost.data(using: String.Encoding.utf8);
request.httpBody = artistPost.data(using: String.Encoding.utf8);
request.httpBody = albumPost.data(using: String.Encoding.utf8);
request.httpBody = yearPost.data(using: String.Encoding.utf8);
request.httpBody = genrePost.data(using: String.Encoding.utf8);
--->>let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
print(response)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Having an issue with the urlsession.shared.datatask line of code. Compiler error says "ambigious reference to member'dataTask(with:completionhandler:)"
What can get this code to work and how can I verify that this information was passed on the app?
The reason you get that error message is because you are passing NSMutableURLRequest where URLRequest is needed.
Changing this line:
let request = NSMutableURLRequest(url:requestURL!)
to this:
var request = URLRequest(url:requestURL!)
should fix it.
But I recommend a little more fixes to make your request successfully sent to the server:
let requestURL = URL(string: "*****")
//You should use `URLRequest` in Swift 3, mutability is represented by `var`
var request = URLRequest(url:requestURL!)
request.httpMethod = "POST"
//UITextField.text can be nil, you should treat nil cases
//(Generally avoid using forced unwrapping `!` as far as you can.)
let song = txt1.text ?? ""
let artist = txt2.text ?? ""
let album = txt3.text ?? ""
let year = txt4.text ?? ""
let genre = txt5.text ?? ""
//`song`,... are all Strings, you have no need to add `as String`
let songPost = "song=" + song
let artistPost = "&artist=" + artist
let albumPost = "&album=" + album
let yearPost = "&year=" + year
let genrePost = "&genre=" + genre
//You need to make a single data containing all params
//(Creating a concatenated String and getting `data` later would be another way.)
var data = Data()
data.append(songPost.data(using: String.Encoding.utf8)!)
data.append(artistPost.data(using: String.Encoding.utf8)!)
data.append(albumPost.data(using: String.Encoding.utf8)!)
data.append(yearPost.data(using: String.Encoding.utf8)!)
data.append(genrePost.data(using: String.Encoding.utf8)!)
request.httpBody = data
let task = URLSession.shared.dataTask(with: request) { data, response, error in
...
Related
I am creating an app, where I am fetching the data from a php. To download the data from the php, I have a func that downloads the data, submits to the model, and then retrieves it whenever needed. Now the issue is, when my data is fetched from the data base, it is not snyc appropriately and getting the same info every where. For example, Name shows the mob phone; street address also shows the same.
here is my code
func download(){
let request = NSMutableURLRequest(url: URL(string: "http://www.some-site.com")!)
request.httpMethod = "POST"
let postString = "id=\(businessID)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: (request as URLRequest), completionHandler: { data, response, error in
let responseString = String(data: data!, encoding: String.Encoding.utf8)
let r = self.convertStringToDictionary(responseString!)
for element in r! {
print("element = \(element)")
let stname = String(describing: element.first!)
let sn = stname.replacingOccurrences(of: "\"STREET_NAME\", ", with: "")
let name = String(describing: element.first!)
let n = name.replacingOccurrences(of: "\"FILE_LOCATION\", ", with: "")
let reverse = element.reversed()
let fileloc = String(describing: reverse.first!)
let f = fileloc.replacingOccurrences(of: "\"BUSINESS_NAME\", ", with: "")
self.model = ProfilePage(fileloc: f, streetname: sn, name: n)
print("Address = \(stname)")
print("Name = \(name)")
print("File Location = \(f)")
DispatchQueue.main.async {
self.setUI()
}
}
if error != nil {
print("error=\(error)")
}
})
task.resume()
}
}
but yes in my output console, i can see all the infor appropriate, its just when i run this, it shows all the info as one
Screenshots
Let me Know is this work for you,
let r = self.convertStringToDictionary(responseString!) // Make sure Your string is successfully converted as NSDictionary else use below
// let r = self.convertStringToDictionary(responseString!) as NSDictionary // if r is dictionary, then convert to NSDictionary
let stname = r["STREET_NAME"] as! String
let name = r["FILE_LOCATION"] as! String
let f = r["BUSINESS_NAME"] as! String
print("Address",stname)
print("Name",name)
print("File Location",f)
DispatchQueue.main.async {
self.setUI()
}
If you confuse, then refer below example
let mydict = ["Hip-Hop Tamizha": 21,"Hip-Hop Tamizha":"Takkaru Takkaru","Michael Jackson":"Beat It","Taylor Swift":"Back to December","Katy Perry":"Fire Works","Selina Gomez":"Love You Like A Love Song Baby","Avril Lavigne":"Slipped Away","Eminem":"The Music Box","Akhil":"Khaab","Hip-Hop Tamizha": 21,"Akhil": 61] as NSDictionary
let hop = mydict["Hip-Hop Tamizha"] as AnyObject
let swift = mydict["Taylor Swift"] as! String
print("The Number:",hop)
print("Taylor Swift song:",swift)
I have read all the other threads but my problem is a mix of those. So I am trying to send some content over to a php server through HTTP in swift. Everything works fine until I append an image base64 content to the body of the http tag. I checked the php backend max post size, wasnt it. I copy pasted the image content that was generated in swift and pasted it in chrome and image was there, so image is not faulty.
This is the sample code of what I have
let url = NSURL(string: "https:example.com/endpoint")
// let session = NSURLSession.sharedSession();
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
var body = "csrf_token=" + (token.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! as String)
body += "&email=" + (email?.text)!
body += "&first_name=" + (firstName?.text)!
body += "&last_name=" + (lastName?.text)!
body += "&password=" + password!.text!
//body += "&image_content=" + imageContent
body += "&confirm_password=" + confirmPassword!.text!
body += "&provider=" + provider
body += "&pictureURL=" + pictureURL
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("https:example.com/", forHTTPHeaderField: "origin")
request.addValue("https:example.com/endpoint", forHTTPHeaderField: "referrer")
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
print(data)
print(response)
return;
}
let dataString = NSString(data :data!, encoding: NSUTF8StringEncoding);
print(dataString)
if ((response as! NSHTTPURLResponse).statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), {
self.performSegueWithIdentifier("loginAfterSignup", sender: nil)
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
print((response as! NSHTTPURLResponse).statusCode)
print("error code, could not sign up and login")
})
}
}
task.resume()
So when I uncomment the line with the base64 string content, I go to the throwback call and it prints the "error".
I have no clue why its not sent through http. Is there a rule I have to obey? Do I have to set a certain http header once I append a large string? Am I missing something here?
Thanks
Yep, it was a stupid Apache settings error. I have previously modified max_post_size and got nothing. However this time I modified the max request body parameter and I could finally send data to the server.
I am trying to work with a swift code to pass vars to php and a response back to swift. this all goes smooth with the following code. This is just a simple peice of code to get things going. It gives me the correct connection and results, how ever i have to pass loads of data which should be in an array i guess. But when i try to send through more data in a array i don't see anything. In php i would explode the results to get them one by one but how do i get loads of values to variables so i can use them again?
below is my code
<?php
require('conn.php');
header('Content-type: application/json');
if($_POST) {
$database =trim ($_POST['database']);
$engine = trim($_POST['engine']);
$name = "William";
$results = Array("name" => $name
);
echo json_encode($results);
}/*end if POST*/
?>
this is the swift code
let data:NSString = ("bfdprofile" as NSString)
let engine:NSString = "account" as NSString
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
let url = NSURL(string:"xxxxx.php")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "data=\(data)&engine=\(engine)"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// set content length
//NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
if let results = NSJSONSerialization.JSONObjectWithData(reply!, options: nil, error: &error) as? [String: String]{
if let name = results["name"]{
labelTestOutput.text = name as? String
}
}
Thanks for the help
You can do it asynchronously with Alamofire library as simple as that:
typealias JSONdic = [String: AnyObject]
let param = ["data": "somedata", "engine": "someEngine"]
Alamofire.request(.POST, URLString: "xxxxx.php", parameters: param).responseJSON() {
(_,_,json,_) in
if let json = json as? JSONdic, name = json["name"] as? String {
// do something with name
}
}
I am trying to send JSON from PHP to iOS Swift.
But when I decode json in Swift, the value is "",
although the key comes out well.
I learned the variables in PHP have to be UTF-8 encoded, but same problem occurs even after the encoding.
Can anyone help me how to solve this issue?
You can just copy & paste both PHP and Swift code.
If I run this code in a web browser, I get
{"upDirection":"\u00ec\u00a2\u0085\u00ed\u0095\u00a9\u00ec\u009a\u00b4\u00eb\u008f\u0099\u00ec\u009e\u00a5"}
This is the code:
<?php
//if(isset($_POST["stationId"]) && isset($_POST["dateTime"])) {
include('simple_html_dom.php');
/* for testing */
$station_id = "923";
$date_time = "201507091750";
$url = "http://m.map.naver.com/pubtrans/inquireSubwayDepartureInfo.nhn?stationID=".$station_id."&inquiryDateTime=".$date_time."00&count=5&caller=mobile_naver_map&output=json";
$html = file_get_contents($url);
//Json to array
$json = json_decode($html, true);
$result = $json["result"];
/**
upDirection
**/
$upDirection = $result["upDirection"];
$upDirection = utf8_encode($upDirection);
// Return as json
$return_json = [
"upDirection" => $upDirection
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($return_json);
//}
?>
And here is the code in swift
func fetchTimeSchedule() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// Send the station ID to PHP
var url: NSURL = NSURL(string: self.timeScheduleUrl)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
// Prepare post data
// station id
let stationId = self.currentViewingStation.id
// datetime
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let year = components.year
let month = components.month < 10 ? "0\(components.month)" : "\(components.month)"
let day = components.day < 10 ? "0\(components.day)" : "\(components.day)"
let hour = components.hour < 10 ? "0\(components.hour)" : "\(components.hour)"
let minutes = components.minute < 10 ? "0\(components.minute)" : "\(components.minute)"
let dateTime = "\(year)\(month)\(day)\(hour)\(minutes)"
var bodyData = "stationId=\(stationId)&dateTime=\(dateTime)"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
println("bodyData:\(bodyData)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error = \(error)")
return
}
if let HTTPresponse = response as? NSHTTPURLResponse {
println("received:\(HTTPresponse.statusCode)")
if HTTPresponse.statusCode == 200 { // Successfully got response
var err: NSError?
if let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) {
// decode json
println(json) // <- Here ******************
}
}
}
}
task.resume()
})
}
This is what the line
println(json) // <- Here ******************
prints out:
Optional({
upDirection = "";
})
i solved this problem with this code:
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "user=mike"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")
With this php
header('Content-Type: application/json; charset=utf-8');
$a1 = $_POST['user'];
$returnValue = array("a1"=>$a1);
echo json_encode($returnValue);
It works, but what I want is to send a video (myvideo.mov)
Somebody help me change to send a video?
I've tried with several images and goes smoothly, I'm not sure but will NSData?
Thank you all!
let pathObject: String = "myImage.png"
let pathMyPhp = "http://myhost.com/etc/uploadFile.php"
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let cDispositionName = "userfile"
let contentDisposition = "Content-Disposition: form-data; name=\"\(cDispositionName)\"; filename=\"\(pathObject)\"\r\n"
let mimeType = "application/octet-stream"
let objUIImage = UIImage(named: pathObject)
let fileExtension = pathObject.pathExtension
var objNSData: NSData = NSData()
let objNSData: NSData = UIImageJPEGRepresentation(objUIImage, 1.0);
let pathPHP = NSURL(string:pathMyPhp)
var err: NSError?
let img = NSURL(string:pathObject)
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
let tempData = NSMutableData()
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(objNSData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
var body = NSMutableData();
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
var request = NSMutableURLRequest(URL: pathPHP!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
request.setValue(contentType, forHTTPHeaderField:"Content-Type")
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:vl_error)
var results = NSString(data:responseData!, encoding:NSUTF8StringEncoding)
println("\(results)")
Thank you very much everyone, I would appreciate any help.