所以我遇到了一个小障碍,我试图访问一个在Alamofire请求函数内部创建的变量。有一点背景为:访问一个隐藏在函数内部深处的变量,在Swift中使用函数外部2
使用SwiftyJSON/Alamofire来访问JSON文件并解析它,有一个访问日期的变量,但日期是RFC 3339格式,现在我创建了一个函数来解析RFC 339中的日期到一个可读的格式,但我现在没有如何访问JSON解析函数中创建的日期变量与日期解析函数一起使用。
//Get the JSON from server
func getJSON() {
Alamofire.request(.GET, "link goes here").responseJSON { (Response) in
if let value = Response.result.value {
let json = JSON(value)
for anItem in json.array! {
let title: String? = anItem["Title"].stringValue
let date: String? = anItem["Date"].stringValue //trying to access this variable outside the function
let body: String? = anItem["Body"].stringValue
self.tableTitle.append(title!)
self.tableDate.append(date!)
self.tableBody.append(body!)
print(anItem["Title"].stringValue)
print(anItem["Date"].stringValue)
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
}
// this date stuff isn't being used yet, because I have no idea how...
public func dateForRFC3339DateTimeString(rfc3339DateTimeString: String) -> NSDate? {
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
let rfc3339DateFormatter = NSDateFormatter()
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return rfc3339DateFormatter.dateFromString(rfc3339DateTimeString)
}
public func userVisibleDateTimeStringForRFC3339DateTimeString(rfc3339DateTimeString: String) -> String? {
let maybeDate = dateForRFC3339DateTimeString(rfc3339DateTimeString)
if let date = maybeDate {
let userVisibleDateFromatter = NSDateFormatter()
userVisibleDateFromatter.dateStyle = NSDateFormatterStyle.MediumStyle
userVisibleDateFromatter.timeStyle = NSDateFormatterStyle.ShortStyle
return userVisibleDateFromatter.stringFromDate(date)
} else {
return nil
}
}
let finalDateStr = userVisibleDateTimeStringForRFC3339DateTimeString(MasterViewController) //now this is where it gets weird, instead of letting me enter the string in the brackets, it defaults to MasterViewController, now I tried to move the date functions to another .swift file (an empty one) and it doesn't do that anymore
所以是的,就是这样,如果任何人都可以提供帮助,将不胜感激。
不能使用:'让convertedDate = dateForRFC3339DateTimeString (rfc3339DateTimeString:anItem [“Date”]。stringValue)'而不是'let date:String? = anItem [“Date”]。stringValue' – Santosh
@Santosh试过了,给了我一个“不能转换类型'NSDate'的值来键入'String?',所以我删除它,现在它给了我'不能下标值类型'JSON',索引类型为'String'' – omar
只需尝试'anItem [“Date”]'并且您需要修改您的方法以接受'NSDate'作为参数类型并相应地修改里面的定义 – Santosh