我正在玩Swift,我在运行项目时遇到了一个奇怪的问题。
我有两个课程: homeViewController 和照片。
这是主要代码:
homeViewController:
class homeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource{
// .... some code...
func publishPhoto(){
var photo = Photo()
// Establecemos el loading
photoDesc.resignFirstResponder()
let loading = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loading.mode = MBProgressHUDModeDeterminate
loading.labelText = "Un segundo por favor...";
var imageData = UIImageJPEGRepresentation(photoInfo["UIImagePickerControllerOriginalImage"] as UIImage, 100.0)
photo.addPhoto()
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
// .... some code ....
}
照片
import Foundation
import UIKit
class Photo: UIViewController{
func addPhoto(){
var homeCtrl = homeViewController()
homeCtrl.photoDesc.resignFirstResponder()
var imageData = UIImageJPEGRepresentation(homeCtrl.photoInfo["UIImagePickerControllerOriginalImage"] as UIImage, 100.0)
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
var parameters = ["user":"admin","password":"123456", "image" : imageData]
manager.POST( "http://misdemos.dev/simpleApi/prueba",
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println("JSON: " + responseObject.description) },
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
}
我在此行中收到错误EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
:
manager.requestSerializer.setValue(" 608c6c08443c6d933576b90966b727358d0066b4&#34 ;, forHTTPHeaderField:" X-Auth-Token")
如果我将addPhoto()代码直接放在homeViewController.publishPhoto中,它可以工作......
这是我第一次使用iOS而且我不知道自己做错了什么。
答案 0 :(得分:2)
尝试在设置标题字段之前创建requestSerializer和responseSerializer。
例如JSON序列化程序:
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFJSONResponseSerializer()
另一种选择是创建这样的请求:
let request: NSMutableURLRequest = NSMutableURLRequest(URL: "http://misdemos.dev/simpleApi/prueba")
request.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
let operation: AFHTTPRequestOperation = AFHTTPRequestOperation(request: request)
// e.g. response is json
operation.responseSerializer = AFJSONResponseSerializer()
operation.setCompletionBlockWithSuccess(...)
operation.start()