How to load HTML string on UIWebView using swift? - html

The Following is the Code I am using to load HTML String on web view:-
let urlAsString = "https://here is my url"
var encryptedStr: String = "merchant_id=\(merchantId)&order_id=\(orderId)&redirect_url=\(redirectUrl)&cancel_url=\(cancelUrl)&language=EN&billing_name=\(billingName)&billing_address=\(billingAddress)&billing_city=\(billingCity)&billing_state=\(billingState)&billing_zip=\(billingZipCode)&billing_country=\(billingCountry)&billing_tel=\(billingTel)&billing_email=\(billingEmail)&delivery_name=\(deliveryName)&delivery_address=\(deliveryAddress)&delivery_city=\(deliveryCity)&delivery_state=\(deliveryState)&delivery_zip=\(deliveryZipCode)&delivery_country=\(deliveryCountry)&delivery_tel=\(deliveryTel)&merchant_param1=additional Info.&merchant_param2=additional Info.&merchant_param3=additional Info.&merchant_param4=additional Info.&payment_option=\(payOptId)&card_type=\(cardType)&card_name=\(cardName)&data_accept=\(dataAcceptedAt)&enc_val=\(encVal!)&issuing_bank=\(issuingBank)&access_code=\(accessCode)&mobile_no=\(mobileNo)&emi_plan_id=\(emiPlanId)&emi_tenure_id=\(emiTenureId)"
print("encryptedStr :: ",encryptedStr)
if isSaveCard!
{
encryptedStr = encryptedStr + ("&saveCard=Y")
}
let myRequestData = NSData(bytes: encryptedStr, length: encryptedStr.lengthOfBytes(using: .utf8))
print("\n\n\n myRequestData :: ",myRequestData.description)
let request: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: urlAsString)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue(urlAsString, forHTTPHeaderField: "Referer")
request.httpMethod = "POST"
request.httpBody = myRequestData as Data
print("\n\n\nwebview :: ",request)
let transResData: Data? = try? NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: nil) // here i am not getting any data
print("transResData ::: \(String(describing: transResData))")
let transResString = String(data: transResData!, encoding: String.Encoding.ascii)
print("\n\n\n*******************************Payload Response Start*******************************\n")
print("\(String(describing: transResString))") // it gives blank space no any HTML Code
print("\n**********************************Payload Response End********************************\n\n\n")
viewWeb.loadHTMLString(transResString!, baseURL: nil)
But not getting any data in variable named transResData. It gives 0 Bytes as Output. Please provide any Code that can Help me in getting Output.
TIA.

Related

Unable to Upload Image and add parameters with POST method multipart/form-data in Swift

Below is the URL requirement for this API: http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/
according to this answer Upload image with multipart form-data iOS in Swift
I have tried below code, but i am unable to add parameters to POST Request and i am unable to call uploadImage method in viewdidload
Here is the code:
func uploadImage(paramName: String, fileName: String, image: UIImage) {
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/")
let boundary = UUID().uuidString
let deviceId: String = "HardcodeDEVICEIDforiTaag222"
let headers = ["deviceid": "deviceId","userType": "personal","key": "5fe42fb3b54543a0bab5667cf96526f8"]
let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"]
let session = URLSession.shared
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = headers as! [String : String]
// Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
// And the boundary is also set here
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
data.append(image.pngData()!)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
// Send a POST request to the URL, with the data we created earlier
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error == nil {
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
if let json = jsonData as? [String: Any] {
print(json)
}
}
}).resume()
}
in the above code i am unable to add parameters let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"] to urlRequest
And How to call uploadImage in viewDidLoad
Please help me with code

MVC Json Parsing - Swift

I get json output from the MVC project. You can see this output in the image below. But I cannot draw this output on the swift side. For example, I sent the value 6 to the id parameter and got the output in postman. Likewise, how can I pull this data on the swift side?
#objc func gorselCEK(){
let url = URL(string: ".../MobilService/KategoriGorsel/")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=\(6)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let sifre = json[""] {
//Doesn't go in here
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
In the postman, it is GET request and in Swift, you're trying to make a POST request.
Change request method to GET
request.httpMethod = "GET"
Update URL with QueryItems
var urlComponent = URLComponents(string:".../MobilService/KategoriGorsel/")!
url.queryItems = [
URLQueryItem(name: "id", value: "6")
]
//Request
var request = URLRequest(url: urlComponent.url)
request.httpMethod = "GET"
No need to set httpBody

SwiftyJSON : How can I add token?

I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?
My code :
let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)
var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
Normally I'm adding token with this code when I use Swift's JSON :
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
Are you making a post/put with this data? Thats would make sense.
I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.
var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
if error == nil {
var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
url.HTTPBody = try! name.rawData()
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
//do something with his response from getting the data
})
} else {
print(error)
}
})
This is kind of a hacky way of doing it but I think its what you are going for

Swift HTTP POST Request Login

Hey I'm trying to figure out this problem for quite some time so now I'm asking you guys for help.
In my Project I'm trying to send a POST request to a website with a login form to access the server.But I somehow don't manage to pass the data.
The website I'm trying to access is https://edu.sh.ch
in the Inspector of my browser I can see it needs a Post method to pass the data :
<form id="form1" name="form1" autocomplete="off" method="post" action="/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp" onsubmit="return(SubmitForm());"></form>
here's my code:
func PostingCredentials(){
let myUrl = NSURL(string: self.manipulatedUrl)
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let form1 = "user_name=MyUsername&password=MyPassword"
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response = \(response)")
// You can print out response object
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
//
println("responseString = \(responseString)")
}
task.resume()
}
Note that self.manipulateUrl equals to the url which shows up when I log in normally and submit my credentials (https://edu.sh.ch/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp)
The Post Function posts something but the response is always some sort of error page( I'm not getting any error in the code but the response of the server is an error)
So for the end my main question are :
whats the problem with my code
where do I have to send my POST method to,to the login page url or the validation url?
Thanks in advance
Some Problem with your webpage. Something is wrong in web coding. Then also you can try below code :
let form1 = "user_name=MyUsername&password=MyPassword"
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "https://edu.sh.ch")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-type")
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
//var dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
}

I am getting Error 400 on sending the postRequest Function to Foursquare's API

The getRequest worked out perfectly and got the code 200 response and the json data. The postRequest function didn't work and returned Error 400. Any ideas on what could be wrong? Maybe my parameters are not stated correctly?!! Thanks
func getRequest(searchString : String) {
let latitude = 44.3
let longitude = 37.2
let latLongUrl = NSURL(string: "https://api.foursquare.com/v2/venues/search?ll=\(latitude),\(longitude)&client_id=\(kFoursquareAppID)&client_secret=\(kFoursquareAppSecret)&v=20150111") //* find a way to pass the date format into the date area with the YYYYMMDD specific format
let searchQueryUrl = NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=\(kFoursquareAppID)&client_secret=\(kFoursquareAppSecret)&v=20150111&ll=\(latitude),\(longitude)&query=\(searchString)")
let searchQuery2 = NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi")
//In the HTTP request, you need to pass in your client ID, client secret, a version parameter, and any other parameters that the endpoint requires:
let task2 = NSURLSession.sharedSession().dataTaskWithURL(latLongUrl!, completionHandler: { (data, response, error) -> Void in
var stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(stringData)
println(response)
})
}
func postRequest(searchString : String) {
let latitude = 44.3
let longitude = 37.2
let latLon = "\(latitude), \(longitude)"
var request = NSMutableURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Setup the Params Dictionary
var params = [
"ll" : latLon,
"client_id" : kFoursquareAppID,
"client_secret" : kFoursquareAppSecret,
"categoryId" : "4bf58dd8d48988d1e0931735",
"v" : "20150111"]
//Setup an Error
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &error)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//Call a completion Handler when this url call is complete
var task = session.dataTaskWithRequest(request, completionHandler: { (data, respose, err) -> Void in
var stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
//Convert the String into a dictionary
var conversionError: NSError?
//This is the way we can convert the data into a dictionary into those keyValue Pairs
var jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: &conversionError) as NSDictionary
println(jsonDictionary) //this will print out the value we are getting as a dictionary in the console.
})
task.resume()
}