从服务器 Objective C 或 Swift 下载文件

Posted

技术标签:

【中文标题】从服务器 Objective C 或 Swift 下载文件【英文标题】:Downloading Files from server Objective C or Swift 【发布时间】:2014-11-13 00:58:37 【问题描述】:

如何将音频文件从我的服务器下载到用户的手机以在应用程序中使用?当我转到网站链接时,JSON 代码是这样出现的

["name":"Lets Party","path":"http:\/\/domain.us\/\/\/audios\/\/Lets Party.wav",
"name":"Let You Know","path":"http:\/\/domain.us\/\/\/audios\/\/Let You Know.wav",
"name":"OMG","path":"http:\/\/domain.us\/\/\/audios\/\/OMG.wav"]

我尝试获取 JSON 并在 Swift 中转换它,但这使我的应用程序崩溃。但是当我放一个博客 JSON 时,它运行良好,没有崩溃。如何在 Swift 或 Objective-C 中做到这一点?

编辑:我现在收到一条错误消息。

当前代码:

        let urlPath = "http://www.domain.us/"

        let url = NSURL(string: urlPath)

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithURL(url, completionHandler: data, response, error -> Void in

            if error != nil 
                println(error)
             else 
                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                println(jsonResult)
            

        )

        task.resume()
    

错误信息:

2014-11-12 20:07:23.652 JSON Practice[6073:284290] CFNetwork SSLHandshake failed (-9847)
2014-11-12 20:07:23.874 JSON Practice[6073:284290] CFNetwork SSLHandshake failed (-9847)
2014-11-12 20:07:24.054 JSON Practice[6073:284290] CFNetwork SSLHandshake failed (-9847)
2014-11-12 20:07:24.055 JSON Practice[6073:284290] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9847)
Error Domain=NSURLErrorDomain Code=-1200 "The operation couldn’t be completed. (NSURLErrorDomain error -1200.)" UserInfo=0x7fc0ba656020 NSErrorFailingURLStringKey=https://www.domain.us/, NSErrorFailingURLKey=https://www.makemeip.us/, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9847, NSUnderlyingError=0x7fc0ba52ebb0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1200.)"

【问题讨论】:

您需要出示您的代码。这也是转义的 JSON,因此如果您使用 NSJSONSerialization 解析它,它将无法正常工作。 对我来说似乎是一个传输错误 - 您是否尝试过调试请求?我的猜测仍然是服务器正在反馈转义(无效)的 json,它不应该那样做。 对不起,我是初学者,所以我真的不明白你刚才说的哈哈。我该怎么办? 【参考方案1】:
//
//  ViewController.swift
//  Test2
//
//  Created by adm on 11/14/14.
//  Copyright (c) 2014 Dabus.Tv. All rights reserved.
//

import UIKit
import Foundation
import AVFoundation

class ViewController: UIViewController 
    @IBOutlet weak var strFiles: UITextView!
    override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        if let url = NSURL(string: "http://www.anyurl.com/") 
            if let loadedString = String(contentsOfURL: url) 
                // file string was sucessfully loaded
                // add the file path + / + filename + extension
                let localUrl = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String) + "/" + "data" + ".db"  // Documents URL as String (local storage path)
                // check local file path url
                if let checkLocalUrl = NSURL(fileURLWithPath: localUrl) 
                    let savedFile = loadedString.writeToURL(checkLocalUrl, atomically: true, encoding: NSUTF8StringEncoding, error: nil) // write to url savedFile will true or false
                    if savedFile 
                        // do whatever
                        self.strFiles.text = "\(self.strFiles.text)path: \(checkLocalUrl)\n"
                        self.strFiles.text = "\(self.strFiles.text)file was sucessfully saved\n"
                    

                    // lets create an ARRAY with your string
                    var arrayLines = ""
                    if let myArrayParsed = loadedString.JSONParseArray() 
                        for elem:AnyObject in myArrayParsed 
                            let name = elem["name"] as String
                            let path = elem["path"] as String
                            arrayLines = "Name: \(name), Path: \(path)"

                            self.strFiles.text = "\(self.strFiles.text)\(arrayLines)\n"
                        
                     else 
                        // could not parse array

                    

                 else 
                    // could not check local url
                
             else 
                // could not load string contents from url
            
         else 
            // invalid url
        
    
    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

extension String 
    func JSONParseArray() -> [AnyObject]? 
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding) 
            if let array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)  as? [AnyObject] 
                return array
            
         else 
            return nil
        
        return [AnyObject]()
    

【讨论】:

你为什么使用旧的 Xcode? Xcode 6.1 是最新的。你应该从 AppStore 下载 是的,只是在学习 swift,我完全忘记了升级 swift 现在将升级并测试代码,我会告诉你谢谢。 非常感谢!你不知道你帮了我多少!你能改变答案中的网址吗哈哈再次感谢!

以上是关于从服务器 Objective C 或 Swift 下载文件的主要内容,如果未能解决你的问题,请参考以下文章

swift 3或objective c中的水平日历视图

如何使用 mailcore 框架或任何框架从 swift/objective c 中的电子邮件代理中获取收件箱?

从 swift 或 Objective-c 向 js 发送事件

如何在 iOS Swift 或 Objective C 中检测 iPhone 卷访问 [关闭]

从 Objective C 类调用 Swift 方法

在 C/C++ 中使用 swift 库?