您需要在
URLRequest实例中提供凭据,例如Swift 3:
let username = "user"let password = "pass"let loginString = String(format: "%@:%@", username, password)let loginData = loginString.data(using: String.Encoding.utf8)!let base64LoginString = loginData.base64EnpredString()// create the requestlet url = URL(string: "http://www.example.com/")!var request = URLRequest(url: url)request.httpMethod = "POST"request.setValue("Basic (base64LoginString)", forHTTPHeaderField: "Authorization")// fire off the request// make sure your class conforms to NSURLConnectionDelegatelet urlConnection = NSURLConnection(request: request, delegate: self)
或在
NSMutableURLRequestSwift 2中:
// set up the base64-enpred credentialslet username = "user"let password = "pass"let loginString = NSString(format: "%@:%@", username, password)let logindata: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!let base64LoginString = loginData.base64EnpredStringWithOptions([])// create the requestlet url = NSURL(string: "http://www.example.com/")let request = NSMutableURLRequest(URL: url)request.HTTPMethod = "POST"request.setValue("Basic (base64LoginString)", forHTTPHeaderField: "Authorization")// fire off the request// make sure your class conforms to NSURLConnectionDelegatelet urlConnection = NSURLConnection(request: request, delegate: self)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)