您好,我是新手,我在程序中遇到了一个问题。我已经在“让defaultStudentId = NSUserDefaults.standardUserDefaults()”中保存了一些数据,但是每次应用程序停止时,都会保存一些数据。 defaultStudentId.objectForKey(“ studentId”)此“ studentId”来自另一个ViewController。...我需要帮助
这是我的代码和错误.....
import UIKit
class OTPViewController: ViewController {
@IBOutlet weak var OTP_code: UITextField!
let defaultStudentId = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func confirm(sender: AnyObject) {
let std_id = defaultStudentId.objectForKey("studentId")
let sendOTPCode = "StudentId=\(std_id)&CODE=\(self.OTP_code.text)&PartnerID=4B67B239CF3735814C063DB89D750481"
let url = NSURL(string: "http://serviceforonair.examonair.com/AndroidService.asmx/VerifyOTPAndActivateStudent")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = sendOTPCode.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
if error != nil{
print(error)
return
}
do{
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
var message : String!
message = responseString?.stringByReplacingCharactersInRange(NSMakeRange(0, 76), withString: "").stringByReplacingOccurrencesOfString("</string>", withString: "")
print(self.defaultStudentId)
}
catch let jsonException{
print(jsonException)
}
}
task.resume()
}
}
错误
2016-08-15 20:14:10.555 DBMCI [21415:143621] *由于未捕获的异常“ NSRangeException”而终止应用程序,原因:“-[__ NSCFString replaceCharactersInRange:withString:]:范围或索引超出范围”
*首先抛出调用堆栈:
(
0 CoreFoundation 0x000000010dcedd85异常预处理+ 165
1 libobjc.A.dylib 0x0000000110159deb objc_exception_throw + 48
2 CoreFoundation 0x000000010dcedcbd + [NSException提高:格式:] + 205
3 CoreFoundation 0x000000010dcb90ad mutateError + 221
4基金会0x000000010e7c887c-[NSString stringByReplacingCharactersInRange:withString:] + 142
5 DBMCI 0x000000010d62de96 _TFFC5DBMCI17OTPViewController7confirmFPs9AnyObject_T_U_FTGSqCSo6NSData_GSqCSo13NSURLResponse_GSqCSo7NSError__T_ + 902
6 DBMCI 0x000000010d622c87 _TTRXFo_oGSqCSo6NSData_oGSqCSo13NSURLResponse_oGSqCSo7NSError__dT__XFdCb_dGSqS__dGSqS0__dGSqS1___dT + 103
7 CFNetwork 0x0000000111118b49 75-[__ NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:] _ block_invoke + 19
8 CFNetwork 0x000000011112b0f2 __49-[__ NSCFLocalSessionTask _task_onqueue_didFinish] _block_invoke + 302
9 Foundation 0x000000010e82f630 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK + 7
10基金会0x000000010e76a805-[NSBlockOperation main] + 101
11 Foundation 0x000000010e74d725-[__ NSOperationInternal _start:] + 646
12 Foundation 0x000000010e74d336 __NSOQSchedule_f + 194
13 libdispatch.dylib 0x000000011197a3eb _dispatch_client_callout + 8
14 libdispatch.dylib 0x000000011196082c _dispatch_queue_drain + 2215
15 libdispatch.dylib 0x000000011195fd4d _dispatch_queue_invoke + 601
16 libdispatch.dylib 0x0000000111962996 _dispatch_root_queue_drain + 1420
17 libdispatch.dylib 0x0000000111962405 _dispatch_worker_thread3 + 111
18 libsystem_pthread.dylib 0x0000000111cb74de _pthread_wqthread + 1129
19 libsystem_pthread.dylib 0x0000000111cb5341 start_wqthread + 13
)
libc ++ abi.dylib:以NSException类型的未捕获异常终止
(lldb)
最佳答案
基本上
let std_id = defaultStudentId.objectForKey("studentId")
返回一个可选值,因此在字符串插值
"StudentId=\(std_id)"
中,您将获得例如"StudentId=Optional(24)"
而不是预期的"StudentId=24"
,这肯定不是您想要的。假设键
studentId
的对象是String
,将上面的行替换为guard let std_id = defaultStudentId.stringForKey("studentId") else { return }
它检查key的值是否存在,并在成功时取消包装可选值,否则退出该方法。
崩溃的错误消息与该行有关
message = responseString?.stringByReplacingCharactersInRange(NSMakeRange(0, 76), withString: "").stringByReplacingOccurrencesOfString("</string>", withString: "")
避免对范围长度进行硬编码,进行计算。如果不能,请检查字符串的长度。
关于ios - NSRangeException swift ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38959019/