miałem taki sam problem z lokalną ścieżkę obrazu & które rozwiązany przez ustawienie właściwej ścieżce
funkcji użytkowych
var TimestampJPGImageName :String {
var stringTimeStamp = "\(NSDate().timeIntervalSince1970 * 1000)"
stringTimeStamp = stringTimeStamp.stringByReplacingOccurrencesOfString(".", withString: "_")
stringTimeStamp = stringTimeStamp.stringByAppendingString(".jpg")
stringTimeStamp = stringTimeStamp.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
return stringTimeStamp
}
func fileUrlForPathComponent(pathComponent: String) -> NSURL?{
let pathDocumentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePath = "\(pathDocumentDirectory)/\(pathComponent)"
let fileUrl = NSURL(fileURLWithPath: filePath)
return fileUrl
}
func fileSaveToDirectory(image: UIImage, name: String?) -> NSURL? {
//let fileManager = NSFileManager.defaultManager()
//fileManager.createFileAtPath(fileUrlToWrite!.path, contents: imageData, attributes: nil)
var fileUrlToWrite : NSURL? = nil
if let fileName : String = name {
fileUrlToWrite = fileUrlForPathComponent(fileName)//.stringByAppendingString(".png")
}else{
fileUrlToWrite = fileUrlForPathComponent(TimestampJPGImageName)//.stringByAppendingString(".png")
}
assert(fileUrlToWrite != nil, "please check filePath")
if (fileUrlToWrite != nil){
let imageData: NSData = UIImageJPEGRepresentation(image, 0.6)!
imageData.writeToFile(fileUrlToWrite!.path!, atomically: false)
return fileUrlToWrite!
}
else{
return nil
}
}
func fileRemoveAtURL(URL : NSURL) ->(success : Bool?, message : String?){
if let path : String = URL.path{
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(path)
}
catch let error as NSError {
return (false, error.localizedDescription)
}
return (true, "file removed!")
}else{
return (false, "invalid path!")
}
}
Złóż wniosek
func requestCreateEvent(){
if (canMakeAPIRequest() == false){
return
}
let imageJPEGname = TimestampJPGImageName
var parameters : Dictionary<String, AnyObject> =
["event[eventName]" : configuration.stringEventName,
"event[images][0][image][imageFile]" : self.imageTaken!,
"event[images][0][image][imageName]" : imageJPEGname,
]
var headers = [String:String]()
headers["Content-Type"] = "multipart/form-data"
let urlpath = URL_CreateEvent.stringByAppendingString("?access_token=\(gblConfiguration!.AppToken!.accessToken)")
var arrayImageURL : Array<NSURL> = []
self.view.showLoader()
Alamofire.upload(.POST, urlpath, headers: headers, multipartFormData: { (multipartFormData) -> Void in
if let dictUpload : Dictionary<String, AnyObject> = parameters {
for (key , value) in dictUpload {
if value.isKindOfClass(UIImage) {
if let image = value as? UIImage{
/*
//Upload Image with Data
if let imageData = UIImageJPEGRepresentation(image, 0.8) {
multipartFormData.appendBodyPart(data: imageData, name: key, fileName: imageJPEGname, mimeType: "image/jpg")
}else if let imageData = UIImagePNGRepresentation(image) {
multipartFormData.appendBodyPart(data: imageData, name: key, fileName: "myImage.png", mimeType: "image/png")
}*/
//Upload Image with URL PATH
if let fileURL : NSURL = fileSaveToDirectory(image, name: imageJPEGname)
{
multipartFormData.appendBodyPart(fileURL: fileURL , name: key)
arrayImageURL.append(fileURL)
}
else {
assert(false, "Unable to save file-name \(imageJPEGname)")
}
}
}
else {
multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: key)
}
}
}
}, encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion:{
encodingResult in
switch encodingResult {
case .Success(let request, let _, let _):
request.responseJSON { response in
//debugPrint(response)
self.view.hideLoader()
if let objResponse : NSHTTPURLResponse = response.response {
if objResponse.statusCode == 201 { //SUCCESS STATUS
for url : NSURL in arrayImageURL {
fileRemoveAtURL(url)
}
let alert = UIAlertView.init(title: AppName, message: "Event Created!", delegate: nil
, cancelButtonTitle: "OK")
alert.show()
self.navigationController?.popToRootViewControllerAnimated(true)
}
else if objResponse.statusCode == 500 {
let alert = UIAlertView.init(title: AppName, message: "Bad access", delegate: nil
, cancelButtonTitle: "OK")
alert.show()
}
}
switch response.result {
case .Success(let JSON): // Error Handling
if let responseDictionary = JSON as? NSDictionary {
if let errors = responseDictionary["errors"] {
if let _ = errors["errors"] as? Array<String>
{
showErrorMessageAlertView(errors, viewdelegate: self)
}
}
else if let error = responseDictionary["error"] as? String,
let errorDescription = responseDictionary["error_description"] as? String
{
let alert = UIAlertView.init(title: error, message: errorDescription, delegate: nil
, cancelButtonTitle: "OK")
alert.show()
}
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
break
case .Failure(let encodingError as NSError):
print(encodingError)
self.view.hideLoader()
showErrorMessageAlertView(encodingError, viewdelegate: nil)
break
default :
self.view.hideLoader()
break
}
}
)
}
Witam! Czy istnieje sposób na uzyskanie prawidłowej ścieżki? Jawnie poprawna ścieżka do pliku w Katalogu dokumentów? –