【发布时间】:2015-08-20 12:53:25
【问题描述】:
如何在 iOS 上发布请求?实际上,当我登录 Facebook 时,它会从登录位置(纬度、经度)获取用户信息,例如用户名。是否可以使用api 链接:http://buddysin.aumkiiyo.com/fbc
我的代码是:
@IBAction func btnAPI(sender: UIButton)
{
//startConnection()
connectToWebAPI()
}
func connectToWebAPI()
{
//setting up the base64-encoded credentials
let id = "1620912344817986"
//let password = "pass"
let loginString = NSString(format: "%@:%@", id)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
//creating the requestz
let url = NSURL(string: "http://buddysin.aumkiiyo.com/fbc")
var request = NSMutableURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sharedSession()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let urlConnection = NSURLConnection(request: request, delegate: self)
request.HTTPMethod = "POST"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
}
else {
// converting the data into Dictionary
var error: NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
println(jsonResult)
}
})
//fire off the request
task.resume()
}
当我运行时,致命错误显示为
`fatal error: unexpectedly found nil while unwrapping an Optional value`
在“jsonResult”中
【问题讨论】:
-
您在哪一行收到此错误?
-
让 jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
-
试试
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as?NSDictionary{ println(jsonResult) } -
当我更改代码时没有错误显示它显示“nil”
-
在我的 o/p 中显示:Optional({ share = { message = " API AUTH FailD"; status = "-1"; }; })