PayU Money Gateway iOS Swift - swift2

I want to integrate the payU Money sdk in my app using swift2.0
I am using this sdk: https://github.com/payu-intrepos/Documentations/wiki/8.1-NEW-iOS-Seamless-SDK-integration
Where to create the test account for testing.

import UIKit
var merchantKey="your live merchant key"
var salt="your live merchant salt"
var PayUBaseUrl="https://secure.payu.in"
class PaymentScreen: UIViewController,UIWebViewDelegate {
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.initPayment()
}
func initPayment() {
var i = arc4random()
let amount = "1"
let productInfo = "Order"
let firstName = "Sample name"
let email = "abc#gmail.com"
let phone = "9999119911"
let sUrl = "https://www.google.com"
let fUrl = "https://www.bing.com"
let service_provider = "payu_paisa"
let strHash:String = self.sha1(String.localizedStringWithFormat("%d%#", i, NSDate()))
let rangeOfHello = Range(start: strHash.startIndex,
end: strHash.startIndex.advancedBy(20))
let txnid1 = strHash.substringWithRange(rangeOfHello)
let hashValue = String.localizedStringWithFormat("%#|%#|%#|%#|%#|%#|||||||||||%#",merchantKey,txnid1,amount,productInfo,firstName,email,salt)
let hash=self.sha1(hashValue)
let postStr = "txnid="+txnid1+"&key="+merchantKey+"&amount="+amount+"&productinfo="+productInfo+"&firstname="+firstName+"&email="+email+"&phone="+phone+"&surl="+sUrl+"&furl="+fUrl+"&hash="+hash+"&service_provider="+service_provider
let url = NSURL(string: String.localizedStringWithFormat("%#/_payment", PayUBaseUrl))
print("check my url", url, postStr)
let request = NSMutableURLRequest(URL: url!)
do {
let postLength = String.localizedStringWithFormat("%lu",postStr.characters.count)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Current-Type")
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding)
myWebView.loadRequest(request)
} catch {
}
}
func webViewDidStartLoad(webView: UIWebView) {
}
func webViewDidFinishLoad(webView: UIWebView) {
let requestURL = self.myWebView.request?.URL
let requestString:String = (requestURL?.absoluteString)!
if requestString.containsString("https://www.google.com") {
print("success payment done")
}
else if requestString.containsString("https://www.bing.com") {
print("payment failure")
}
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print("double failure")
}
func sha1(toEncrypt:String) -> String {
let data = toEncrypt.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joinWithSeparator("")
}
}

// Swift 4
import UIKit
import SystemConfiguration
import Foundation
class PayUMoneyViewController: UIViewController, UIWebViewDelegate, UIAlertViewDelegate {
#IBOutlet weak var webView: UIWebView!
var merchantKey = "YOUR_MARCHANT_KEY"
var salt = "YOUR_SALT_KEY"
var PayUBaseUrl = "https://secure.payu.in"
var SUCCESS_URL = "https://www.payumoney.com/payments/guestcheckout/#/success"
var FAILED_URL = "https://www.PayUmoney.com/mobileapp/PayUmoney/failure.php"
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var request = NSMutableURLRequest()
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
self.payPayment()
self.navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PayUMoneyViewController.back(sender:)))
self.navigationItem.leftBarButtonItem = newBackButton
}
#objc func back(sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Cancel !", message: "Do you really want to cancel the transaction ?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: cancelTransaction))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func cancelTransaction( action : UIAlertAction)
{
_ = navigationController?.popToRootViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func payPayment() {
var i = arc4random()
let amount = "1"
let productInfo = "Transport"
let firstName = USER_FIRST_NAME // Geet
let email = USER_EMAIL // geetbasakare#gmail.com
let phone = USER_MOBILE_NO // 1234567890
let sUrl = "https://www.google.com"
let fUrl = "https://www.bing.com"
let service_provider = "payu_paisa"
let strHash:String = self.sha1(toEncrypt: String.localizedStringWithFormat("%d%#", i, NSDate()));
let r1 = strHash.range(of: strHash)!
// String range to NSRange:
let n1 = NSRange(r1, in: strHash)
print((strHash as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = Range(n1, in: strHash)!
print(strHash.substring(with: r2))
let rangeOfHello = Range(n1, in: strHash)!
let txnid1 = strHash.substring(with: rangeOfHello)
let hashValue = String.localizedStringWithFormat("%#|%#|%#|%#|%#|%#|||||||||||%#",merchantKey,txnid1,amount,productInfo,firstName,email,salt)
let hash = self.sha1(toEncrypt: hashValue)
let postStr = "txnid="+txnid1+"&key="+merchantKey+"&amount="+amount+"&productinfo="+productInfo+"&firstname="+firstName+"&email="+email+"&phone="+phone+"&surl="+sUrl+"&furl="+fUrl+"&hash="+hash+"&service_provider="+service_provider
let url = NSURL(string: String.localizedStringWithFormat("%#/_payment", PayUBaseUrl))
print("check my url", url as Any, postStr)
let request = NSMutableURLRequest(url: url! as URL)
do {
let postLength = String.localizedStringWithFormat("%lu",postStr.characters.count)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Current-Type")
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postStr.data(using: String.Encoding.utf8)
webView.loadRequest(request as URLRequest)
} catch {
print(error)
}
}
func webViewDidFinishLoad(_ webView: UIWebView) {
let requestURL = self.webView.request?.url
let requestString:String = (requestURL?.absoluteString)!
if (requestString == SUCCESS_URL) {
print("success payment done")
}
else if (requestString == FAILED_URL) {
print("payment failure")
}
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("double failure")
}
func sha1(toEncrypt: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
if let data = toEncrypt.data(using: String.Encoding.utf8) {
let value = data as NSData
CC_SHA512(value.bytes, CC_LONG(data.count), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
/*
func sha1(toEncrypt:String) -> String {
var data = toEncrypt.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA512_DIGEST_LENGTH))
_ = data.withUnsafeBytes {messageBytes in
CC_SHA512(messageBytes, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joined(separator: "")
}
*/
}

You can create a test account as described in the following help documentation, and you need not perform KYC in this regard. Later, you can use the Key and Salt on the Payment Gateway page of the Dashboard.
https://devguide.payu.in/low-code-web-sdk/getting-started-low-code-web-sdk/register-for-a-test-merchant-account/

Related

I want to search in TableView using UISearchBar

I have a Big image of video then the user image who uploaded it and video title and description in Table View Cell. using searcher I am searching but only the title changes video image description etc remains that of the first index please help.
Here's the code.
I am bringing data using alamofire in 3 arrays Video_User, Video_Image,
Video_Name and searching on the basis of Video_Name.
#IBOutlet weak var tableview: UITableView!
var Video_User = [String]()
var Video_Image = [String]()
var Video_Name = [String]()
var img = ""
var name = ""
var pass = ""
var searchingvideos = [String]()
var searching = false
override func viewDidLoad()
{
super.viewDidLoad()
getData()
}
func getData()
{
let urlString = "\(AppDelegate.url)get_vid"
Alamofire.request(urlString, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON
{
response in
print(response.request as Any)
print(response.response as Any)
print(response.data as Any)
print(response.result as Any)
switch response.result
{
case .success:
if let JSON = response.result.value
{
let dlc = (JSON as! NSDictionary)
print(dlc)
let outPut = dlc.value(forKey: "get_vidResult") as! NSArray
for item in outPut
{
let tempitem = item as! NSDictionary
print(tempitem)
self.Video_Name.append(tempitem.value(forKey: "VideoName") as! String)
self.Video_User.append(tempitem.value(forKey: "UserName") as! String)
self.Video_Image.append(tempitem.value(forKey: "VideoImage") as! String)
}
self.tableview.reloadData()
}
case .failure(let error):
print(error)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching
{
return searchingvideos.count
}
else
{
return Video_Name.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:VideoCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! VideoCell
cell.V_Header.text = Video_Name[indexPath.row]
cell.V_Footer.text = Video_User[indexPath.row]
cell.V_Image.sd_setImage(with: URL(string: "\(AppDelegate.img_url)\(Video_User[indexPath.row]).jpg"), placeholderImage: #imageLiteral(resourceName: "v"))
cell.U_Image.sd_setImage(with: URL(string: "\(AppDelegate.img_url)\(Video_Image[indexPath.row]).jpg"), placeholderImage: #imageLiteral(resourceName: "v"))
if searching
{
cell.V_Header.text = searchingvideos[indexPath.row]
}
else
{
cell.V_Header.text = Video_Name[indexPath.row]
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
searchingvideos = Video_Name.filter({$0.uppercased().prefix(searchText.count) == searchText.uppercased() })
searching = true
tableview.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
}

Swift 2 How do I isolate resources in a series of NSMutableURLRequests?

Assume I've already logged to two accounts and have obtained unique session cookies for each.
When executing ViewController.run(), which uses nested closures, a series of 80 unique URL requests is made (40 for each of the two accounts) .
Though I'm able to make all 80 unique URL requests, somehow one account will sometimes make a request of a URL that only the other account should be making.
I'm pretty certain the resources between each account as well as each account's request are isolated. Both executions of run() construct their own instances of Visit(_:), URLVisitor(_:) and Request(_:).
Note: assume that neither account's username array contains a username that the other has in it's array.
ViewController.swift
func run(completion: () -> Void) {
// 40 usernames appended to array
var usernames: [String] = ["username1",..., username40]
for username in usernames {
let visit = Visit()
visit.sessionCookie = sessionCookie
visit.visitProfile(username) {
NSThread.sleepForTimeInterval(5.0)
}
}
}
Visit.swift
var contentsOfURL = NSString()
var sessionCookie = String()
func visitprofile(username: String, completion: () -> Void) {
let url = "https://www.someurl.com/profile/\(username)"
let encodedURL = url.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLFragmentAllowedCharacterSet()),
URL = NSURL(string: encodedURL!)
let vis = URLVisitor(URL: URL!)
vis.sessionCookie = self.sessionCookie
vis.execute {
if vis.containsString(profileName) {
print("\(profileName) visited: OK")
} else {
print("\(profileName) visited: FAIL")
}
completion()
}
}
URLVisitor.swift
var contentsOfURL = NSString()
var sessionCookie = String()
var URL = NSURL()
init(URL: NSURL) {
self.URL = URL
}
func execute(completion: () -> Void) {
let request = Request()
request.sessionCookie = self.sessionCookie
request.accessToken = self.accessToken
request.sessionCookie = self.sessionCookie
request.sendRequest(self.URL, completion: () -> Void) {
self.sessionCookie = request.sessionCookie
self.contentsOfURL = request.contentsOfURL
completion()
}
}
Request.swift: NSObject, NSURLSessionDelegate
var contentsOfURL = NSString()
var responseCookies = String()
var sessionCookie = String()
func sendRequest(URL: NSURL, completion: () -> Void) {
var request = NSMutableURLRequest(URL: URL)
var session = NSURLSession.sharedSession()
var config = NSURLSessionConfiguration.defaultSessionConfiguration()
if sessionCookie != "" {
config.HTTPCookieStorage = nil
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
request.setValue(sessionCookie, forHTTPHeaderField: "Cookie")
session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
}
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request) { (data, response, error) in
let response = response as! NSHTTPURLResponse
do {
self.contentsOfURL = try NSString(contentsOfURL: URL, encoding: NSUTF8StringEncoding)
} catch{
}
if self.sessionCookie == "" {
self.sessionCookie = // obtained here during login
}
completion()
}
task.resume()
}

Swift 2 Adding callouts to annotations

I'm having extreme difficulty having callouts added to my annotations. I've removed any attempt at adding the callout from the code below.
The annotations are added at the bottom of the updateVisiblePins function
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
var landmarkToPass: String!
var rowIndex: Int!
struct MyVars {
static var prevLoc = CLLocation()
static var region = MKCoordinateRegion()
static var landmarks = [Landmark]()
static var landmark: Landmark = Landmark(title: String(), locationName: String(), discipline: String(), coordinate: CLLocationCoordinate2D())
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
var landmarks: [Landmark] = [Landmark]()
loadInitialData()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var prevLoc = MyVars.prevLoc
let userLoction: CLLocation = locations[0]
let distance = calculateDisatnceBetweenTwoLocations(prevLoc, destination: userLoction)
if prevLoc != userLoction {
prevLoc = userLoction
MyVars.prevLoc = userLoction
if distance > 5 {
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
MyVars.region = MKCoordinateRegionMake(location, span)
self.mapView.showsUserLocation = true
self.mapView.setRegion(MyVars.region, animated: true)
updateVisiblePins()
} else {
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let span = mapView.region.span
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
MyVars.region = MKCoordinateRegionMake(location, span)
self.mapView.showsUserLocation = true
updateVisiblePins()
}
}
}
func calculateDisatnceBetweenTwoLocations(source:CLLocation,destination:CLLocation) -> Double{
var distanceMeters = source.distanceFromLocation(destination)
var distanceKM = distanceMeters / 1000
return distanceKM
}
func updateVisiblePins() {
for (index, landmark) in MyVars.landmarks.enumerate() {
let landmarkLat = landmark.coordinate.latitude
let landmarkLon = landmark.coordinate.longitude
let userLocation = locationManager.location
let landmarkLocation = CLLocation(latitude: landmarkLat, longitude: landmarkLon)
let distance = calculateDisatnceBetweenTwoLocations(userLocation!, destination: landmarkLocation)
if distance < 30 {
mapView.addAnnotation(landmark)
} else {
if rowIndex != nil {
if index == rowIndex{
self.mapView.addAnnotation(landmark)
} else {
mapView.removeAnnotation(landmark)
}
}
}
}
}
func loadInitialData() {
// 1
let fileName = NSBundle.mainBundle().pathForResource("PublicLandmark", ofType: "json")
var data: NSData = NSData()
do {
data = try NSData(contentsOfFile: fileName!, options: [])
} catch {
}
// 2
var jsonObject: AnyObject!
do {
jsonObject = try NSJSONSerialization.JSONObjectWithData(data,
options: [])
} catch {
}
// 3
if let jsonObject = jsonObject as? [String: AnyObject],
// 4
let jsonData = JSONValue.fromObject(jsonObject)?["data"]?.array {
for landmarkJSON in jsonData {
if let landmarkJSON = landmarkJSON.array,landmark = Landmark.fromJSON(landmarkJSON) {
MyVars.landmarks.append(landmark)
}
}
}
}
}
The mapView.delegat = self line needs to be added to viewDidLoad() function.

In change of Swift 2 Extra argument ' error' in call

Upgrade to Xcode 7 Swift 2 and SDK for iOS 9. I get the error "extra argument" error "in call" my code is:
let myUrl = NSURL(string: "http://localhost/SwiftAppAndMySQL/scripts/registerUser.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "userEmail=\(userEmail)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue())
{
spinningActivity.hide(true)
if error != nil {
self.displayAlertMessage(error.localizedDescription)
return
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json {
var userId = parseJSON["userId"] as? String
if( userId != nil)
{
var myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
}
}).resume()
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler ) asks you for 3 optionals arguments and you're giving 3 forceds unwrapping arguments.
try change
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data:NSData!, response:NSURLResponse!, error:NSError!)
to
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?)
Now is working, I replaced the previous code with this::
let myUrl = NSURL(string: "http://dcapp1.testingview.com/DryCleanAppClientes/scripts/registerUser.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "userEmail=\(userEmail)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
print(postString)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue())
{
spinningActivity.hide(true)
if error != nil {
self.displayAlertMessage(error!.localizedDescription)
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if let parseJSON = json {
let userId = parseJSON["userId"] as? String
if( userId != nil)
{
let myAlert = UIAlertController(title: "Mensaje", message: "¡Registro exitoso!", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
} catch _ as NSError {
}
}
}).resume()
}

How can I send apikey for authenticaion using Swift in OSX?

I am building a Mac App using Swift. Here is my code
import Cocoa
import AppKit
import Foundation
class ViewController: NSViewController {
#IBOutlet var Email: NSTextField!
#IBOutlet var Password: NSSecureTextField!
#IBAction func signup(sender: AnyObject) {
let signup_url = NSURL(string: "https://my_own_domain.com")
NSWorkspace.sharedWorkspace().openURL(signup_url!)
}
#IBOutlet var progress: NSProgressIndicator!
#IBAction func Signin(sender: AnyObject) {
self.progress.hidden = false
self.progress.startAnimation(self)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let userPasswordString = "\(Email.stringValue):\(Password.stringValue)"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil)
let authString = "Basic \(base64EncodedCredential)"
println("\(authString)")
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
var running = false
let url = NSURL(string: "https://my_own_domain.com/api/v3/auth/token/")
let task = session.dataTaskWithURL(url!) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
self.progress.stopAnimation(self)
self.progress.hidden = true
if httpResponse.statusCode == 401 {
self.progress.hidden = true
let alertPopup:NSAlert = NSAlert()
alertPopup.addButtonWithTitle("OK")
alertPopup.informativeText = "Mistakes happen. Go and Enter correctly now :)"
alertPopup.messageText = "Please Enter Valid Credentials"
alertPopup.runModal()
}
running = false
if let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
println("\(dirs[0])")
let path = dirs[0].stringByAppendingPathComponent("user_apikey_details.json")
let path_file = dirs[0].stringByAppendingPathComponent(path)
var jsonData = NSData(contentsOfFile: path_file, options: nil, error: nil)
let folder_path = dirs[0].stringByAppendingPathComponent("/SYNC_FOLDER")
let filemanager: NSFileManager = NSFileManager()
let folder = filemanager.createDirectoryAtPath(folder_path, withIntermediateDirectories: true, attributes: nil, error: nil)
dataString?.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
if let file_data = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
println("\User apikey has been saved to file. file data is: \(file_data)")
var string: String = file_data
var split = string.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
var split2 = split.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
var splitted_data = split2.componentsSeparatedByString(" ")
println("\(splitted_data)")
var savestring : NSUserDefaults = NSUserDefaults.standardUserDefaults()
savestring.setObject(splitted_data[1], forKey: "SavedString")
savestring.synchronize()
}
}
}
running = false
}
running = false
task.resume()
while running {
println("Connecting...")
sleep(1)
}
}
override func viewDidLoad() {
super.viewDidLoad()
progress.hidden = true
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Here in the above code, I am authenticating to my api and getting the json data of apikey and storing it in one file. In splitted_data[1], i get only apikey here.
I have a requirement to get data from other url of the same api. For getting the data, now I need to send the apikey for that api. Previously I have done with the chromeapp and I used to sent as apikey yashwanthbabu.gujarthi#gmail.com:5c9ba3e84ec8ebd1062ddc4e94e5f0c15df8cade.
In this way i used to send the apikey to GET and POST the data. But in swift I used to do the same but it was not authenticating.
In the same way you can send the apikey for the url.
let config1 = NSURLSessionConfiguration.defaultSessionConfiguration()
let apikeystring = "apikey \(self.Email.stringValue):\(splitted_data[1])"
config1.HTTPAdditionalHeaders = ["Authorization" : apikeystring]
let session1 = NSURLSession(configuration: config1)
let url1 = NSURL(string: "https://my_own_domain.com/api/v3/some_thing")
let task1 = session1.dataTaskWithURL(url1!) {
(let data1, let response1, let error1) in
if let httpResponse1 = response1 as? NSHTTPURLResponse {
let dataStr = NSString(data: data1, encoding: NSUTF8StringEncoding)
let mem_path = dirs[0].stringByAppendingPathComponent("mems.json")
let mem_file = dirs[0].stringByAppendingPathComponent(mem_path)
dataStr?.writeToFile(mem_path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
if let mem_data = String(contentsOfFile: mem_path, encoding: NSUTF8StringEncoding, error: nil) {
println("FILE_DATA\(mem_data)")
}
}
Hope this will definitely work for you.

Resources