我想用基本身份验证发出http请求。我试着遵循这个主题:click here。但Xcode告诉我
httpResponse后的错误请求
我不知道为什么从今天早上起。也许任何人都有一个比我在网上找到的更有趣的想法? :)
这是我的代码:
func topRefresh(sender:AnyObject){
var list=Array<Notification>()
//credential
let credentialLogin = NSUserDefaults.standardUserDefaults().objectForKey("login") as! String
let credentialPassword = NSUserDefaults.standardUserDefaults().objectForKey("password") as! String
// set up the base64-encoded credentials
let loginString = NSString(format: "%@:%@", credentialLogin, credentialPassword)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
// create the request
let url = NSURL(string: jsonLink)!
let request = NSMutableURLRequest(URL: url)
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.HTTPMethod="GET"
let paramString="login="+credentialLogin
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
if (httpResponse.statusCode == 200) {
do{
if (data != nil){
self.notificationsDisplayed.removeAll()
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!,options: .AllowFragments)
list=self.parseJson(jsonDict)
if (self.notifications.count==0){
self.notifications=self.copyArray(list)
list.removeAll()
}else{
//compare new data with past data
while(list.count>0){
print(list.count)
let tmp=list.last
for notification in self.notifications {
if(tmp!.id==notification.id){
list.removeLast()
break
}else{
self.notifications.insert(tmp!, atIndex: 0)
list.removeLast()
break
}
}
}
}
self.orderByDate(&self.notifications)
self.notificationsDisplayed=self.copyArray(self.notifications)
self.applyFilter()
print("Data parsed")
}else{
print("Data is empty")
}
}catch {
print("Error with Json: \(error)")
}
}else{
print("HTTP Error")
}
self.refreshControl?.endRefreshing()
print("Finished")
}
task.resume()
}
答案 0 :(得分:1)
我在代码中使用以下内容来创建包含身份验证的默认会话:
max