我正在使用Swift构建一个Mac应用程序。这是我的密码
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.
}
}
}
在上面的代码中,我对我的api进行身份验证,获取apikey的json数据并将其存储在一个文件中。在splitted_data[1]中,这里只有一个apikey。
我需要从同一api的其他url获取数据。为了获取数据,现在我需要发送该api的apikey。以前我用过chromeapp,以前我用
apikey [email protected]:5c9ba3e84ec8ebd1062ddc4e94e5f0c15df8cade
发送。我用这种方式发送apikey来获取和发布数据。但在斯威夫特,我也曾这样做过,但那不是认证。
最佳答案
以同样的方式发送url的apikey。
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)")
}
}
希望这对你一定有用。
关于macos - 如何在OSX中使用Swift发送用于身份验证的api key ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27899290/