2016-07-14 4 views
27

나는 새로운 아이폰 OS 10/스위프트 3을 NSData 교체를 반환하는 코드를 입력했습니다 (?) : 데이터Swift 3의 '데이터'유형에 해당하는 writeToFile이 있습니까?

if let jpegData = UIImageJPEGRepresentation(newImage, 0.8) { ... } 

을 나는 디스크에 이미지를 기록 할이, 그러나있는 NSData의 writeToFile: 메서드는이 클래스에 대한 존재하지 않습니다 . writeToURL: 메서드가 있지만 파일 경로 (및 구성 요소 추가)에서 작동하지 않는 것 같습니다.

사람은 스위프트 두 경우를 예전처럼 지금,이 작업을 수행 할 방법을 명확히 수 :

jpegData.writeToFile(imagePath, atomically: true) 

감사합니다!

답변

68

write(to: fileURL)을 사용하십시오. 당신이 정말 path와 함께 붙어있는 경우

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("test.jpg") 

do { 
    try jpegData.write(to: fileURL, options: .atomic) 
} catch { 
    print(error) 
} 

또는, URL A와 그 변환 : 예를 들어

일반적으로,

do { 
    try data.write(to: URL(fileURLWithPath: path), options: .atomic) 
} catch { 
    print(error) 
} 

을하지만, 그것은 전체에 URL 참조를 사용하는 것이 바람직입니다 귀하의 코드는 요즘, 경로 문자열의 사용을 은퇴.

+1

환상적입니다. 롭 감사합니다. .atomic으로 전환 해 주셔서 감사합니다. –

+2

애플은 URL 기반 파일 API쪽으로 이동하고 경로 (String) 기반 객체를 비추천 (deprecating)하는 것으로 보인다. –

+0

대단히 그렇습니다. 그러나 이상한 예외가 있습니다 (예 : [UIImage (contentsOfFile :)'] (https://developer.apple.com/documentation/uikit/uiimage/1624112-init), 파일 URL 변환 없음) . – Rob